JavaScript - 过滤嵌套数组 [英] JavaScript - Filter Nested Arrays
本文介绍了JavaScript - 过滤嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 javascript 中过滤一个数组,并且在嵌套数组时遇到困难.
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" }]
]
可以找到两个例子:https://jsfiddle.net/vjt45xv4/
任何在嵌套数组上找到合适结果的提示将不胜感激.
Any tips for finding the appropriate result on the nested array would be much appreciated.
谢谢!
推荐答案
展平数组然后过滤它:
arr.reduce(function(a,b) { return a.concat(b); })
.filter(function(obj) { return obj.id == ID; });
这篇关于JavaScript - 过滤嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文