JavaScript - nested array filter

I am trying to filter an array in javascript and am afraid when the array is nested.

At the moment, the most remote I could get is flat array filtering:

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);

Although the above does not work if the array looks like this:

var arr2 = [
    [{ id : 1, name: "a" },{ id : 2, name: "b" }],
    [{ id : 3, name: "c" },{ id : 4, name: "d" }]
] 

Two examples can be found: https://jsfiddle.net/vjt45xv4/

Any advice on finding a suitable result for a nested array would be greatly appreciated.

Thanks!

+4
source share
2 answers

Flatten array and then filter :

arr.reduce(function(a,b) { return a.concat(b);  })
   .filter(function(obj) { return obj.id == ID; });
+9
source
arr2.filter(function( obj ) {
    obj.filter(function(d) { if(d.id == ID){ 
    result = d;}})});
alert(result.name);

, , . , , , ( ) .

arr2.forEach(function(d) {
d.forEach(
  function(dd){ alert(dd.id);if(dd.id==ID){result=dd; }}
  );
});
alert(result.name);

: minitech , forEach.

+1

Source: https://habr.com/ru/post/1607325/


All Articles