I have JSON data which has structure as follows:
data = [
{
"id": 100,
"floorplans": [
{
"bhk": 1,
...some other fields
},
{
"bhk": 3,
...some other fields
},
{
"bhk": 2,
...some other fields
}
]
},
{
"id": 200,
"floorplans": [
{
"bhk": 1.5,
...some other fields
},
{
"bhk": 1,
...some other fields
},
{
"bhk": 2.5,
...some other fields
}
]
},
{
"id": 300,
"floorplans": [
{
"bhk": 1,
...some other fields
},
{
"bhk": 4,
...some other fields
},
{
"bhk": 2,
...some other fields
}
]
}]
Now I have another array lets say tempArray = [ 2, 3] now I only want to filter those objects from data array which has bhk === 2 i.e tempArray[0] or bhk === 3 i.e tempArray[1]
I am not able to understand how to filter such data ? Below code doesn't work I am not able to find any example of such filtering.
code:
var filtered_data = data.filter((val) => {
return val.floorplans.indexOf(tempArray[0]) !== -1;
})
Now as tempArray has 2 and 3 elements so I want to display only data[0] and data[2] object and not data[1] because data[1] doesnot contain neither 2 nor 3.
You can simply use Array.filter() with Array.some() and Array.includes() to filter out the data in which bhk is present in temp array.
Try the following:
let data = [ { "id": 100, "floorplans": [ { "bhk": 1 }, { "bhk": 3 }, { "bhk": 2 } ] }, { "id": 200, "floorplans": [ { "bhk": 1.5 }, { "bhk": 1 }, { "bhk": 2.5 } ] }, { "id": 300, "floorplans": [ { "bhk": 1 }, { "bhk": 4 }, { "bhk": 2 } ] }];
let temp = [2, 3];
let filterData = data.filter(a => a.floorplans.some(e => temp.includes(e.bhk)));
console.log(filterData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With