JavaScript - 过滤嵌套数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32571491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Filter Nested Arrays
提问by Steve
I'm trying to filter an array in javascript, and am struggling when the array is nested.
我正在尝试在 javascript 中过滤一个数组,并且在嵌套数组时很挣扎。
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/
可以找到这两个例子:https: //jsfiddle.net/vjt45xv4/
Any tips for finding the appropriate result on the nested array would be much appreciated.
任何在嵌套数组上找到适当结果的提示将不胜感激。
Thanks!
谢谢!
回答by John Strickler
回答by hunters30
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.
编辑:正如 minitech 提到的,如果只使用 forEach,它的工作方式相同。