I'm trying to filter an array in javascript, and am struggling when the array is nested.
At the moment, the furthest I've been able to get is filtering a flat array:
var ID = 3
var arr = [{ id : 1, name: "a" }, { id : 2, name: "b" }, { id : 3, name: "c" }]
var result = arr.filter(function( obj ) {return obj.id == ID;});
alert(result[0].name);
Though the above doesn't work if the array looks like this instead:
var arr2 = [
[{ id : 1, name: "a" },{ id : 2, name: "b" }],
[{ id : 3, name: "c" },{ id : 4, name: "d" }]
]
The two examples can be found: https://jsfiddle.net/vjt45xv4/
Any tips for finding the appropriate result on the nested array would be much appreciated.
Thanks!
You can access a nested array of objects either using dot notation or bracket notation. JavaScript has only one data type which can contain multiple values: Object. An Array is a special form of an object. Both arrays and objects expose a key -> value structure.
arr2.filter(function(obj) {
obj.filter(function(d) {
if(d.id == ID) {
result = d;
}
})
});
alert(result.name);
Hope this is what you were looking for. Rather than flattening the data here I went into the nested array till the point where it was flat(and matching) and set the result there.
arr2.forEach(function(d) {
d.forEach(
function(dd){
alert(dd.id);
if (dd.id==ID){
result=dd;
}
}
);
});
alert(result.name);
Edit: As minitech mentioned its same working if just using forEach.
Flatten the array then filter it:
arr.reduce(function(a,b) { return a.concat(b); })
.filter(function(obj) { return obj.id == ID; });
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