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.
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")))
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.