Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter nested data based on multiple options in javascript?

Tags:

javascript

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.

like image 222
fun joker Avatar asked Dec 07 '25 05:12

fun joker


1 Answers

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);
like image 138
amrender singh Avatar answered Dec 08 '25 19:12

amrender singh