user3872094
user3872094

Reputation: 3351

Filtering nested js object array using javascript

I'm trying to get data from a nested js object and here is my input.

var data = 
    [ [ { Id: '123', Name: 'Abc', Amount: 110000 } 
      , { Id: '567', Name: 'DEF', Amount:  98000 } 
      , { Id: '345', Name: 'XYZ', Amount: 145000 } 
      ] 
    , [ { Id: '656', Name: 'Abc', Amount: 110000 } 
      , { Id: '223', Name: 'DEF', Amount:  98000 } 
      , { Id: '897', Name: 'XYZ', Amount: 145000 } 
    ] ] 

And here when I want to get data of 223.
I am not much aware of how we can do it in nested js object .
In regular js object array, I use the filter method like below.

var result= data.filter(element => ((element.Id == "223")).

But how Can I do it in case of nested js object (in ES6)?

I referred to post here and made a small fiddle here, which isn't working as expected.

Upvotes: 0

Views: 73

Answers (2)

Mechanic
Mechanic

Reputation: 5380

you can .flat() the data array the first, then just do a simple filter on it and search for the Id you want; or filter array recursively and then search for the Id you want. snippet below demonstrates the second way

let result = data.map( array =>  
   array.filter( item => item.Id === "223" )
).flat();

var data = 
    [ [ { Id: '123', Name: 'Abc', Amount: 110000 } 
      , { Id: '567', Name: 'DEF', Amount:  98000 } 
      , { Id: '345', Name: 'XYZ', Amount: 145000 } 
      ] 
    , [ { Id: '656', Name: 'Abc', Amount: 110000 } 
      , { Id: '223', Name: 'DEF', Amount:  98000 } 
      , { Id: '897', Name: 'XYZ', Amount: 145000 } 
    ] ];

let result = data.map( array =>  array.filter( item => item.Id === "223" )).flat();


console.log(result);

Upvotes: 1

dave
dave

Reputation: 64657

I'd just flatten it first (first console log), unless you want the whole "outer" array, in which case just do .find twice:

var data = [
  [{
      "Id": "123",
      "Name": "Abc",
      "Amount": 110000
    },
    {
      "Id": "567",
      "Name": "DEF",
      "Amount": 98000
    },
    {
      "Id": "345",
      "Name": "XYZ",
      "Amount": 145000
    }
  ],
  [{
      "Id": "656",
      "Name": "Abc",
      "Amount": 110000
    },
    {
      "Id": "223",
      "Name": "DEF",
      "Amount": 98000
    },
    {
      "Id": "897",
      "Name": "XYZ",
      "Amount": 145000
    }
  ]
];


var result = data.flat().filter(element => element.Id == "223");
console.log(result);

console.log(data.find(el => el.find(item => item.Id === "223")))

Upvotes: 1

Related Questions