I would like to know how to iterate through a nested array of objects in Javascipt? I have a sample object named obj. I want to retrieve the object based on condition 'in' is 'string' and 'out' 'number'.
// tried got stuck
const output = [];
myList.forEach(entry => {
Object.keys(entry).forEach(key => {
const entity = entry[key][0];
if (entity.in === "string" && entity.out === "number") {
output.push(entity);
}
});
});
var obj = [{
"ston": [{
"id": "identity1",
"in": "string",
"out": "number",
"value": 10
},{
"id": "identity2",
"in": "string",
"out": "number",
"value": 10
}],
"nton": [{
"id": "identity1",
"in": "number",
"out": "number",
"value": 20
},{
"id": "identity2",
"in": "number",
"out": "number",
"value": 30
}]
}]
Expected Output
[{
"id": "identity1",
"in": "string",
"out": "number",
"value": 10
},{
"id": "identity2",
"in": "string",
"out": "number",
"value": 10
}]
You can use rebuild that object to a nested array then flatten and finally filter
.
var obj = [
{
"ston": [
{"id": "identity1", "in": "string", "out": "number", "value": 10},
{"id": "identity2", "in": "string", "out": "number", "value": 10}
],
"nton": [
{"id": "identity1", "in": "number", "out": "number", "value": 20},
{"id": "identity2", "in": "number", "out": "number", "value": 30}
]
}
];
const tmp = obj.map(e => Object.entries(e).map(([k, v]) => v)).flat(3)
const rs = tmp.filter(e => e.out==='number' && e.in ==='string')
console.log(rs)
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