简体   繁体   English

使用forEach过滤数组项

[英]Filter array items using forEach

I have one question about filter array in forEach. 我在forEach中有一个关于过滤器数组的问题。 So I would like filter (bigger than in example) array using outside variable filterKey . 所以我想使用外部变量filterKey过滤(比示例更大)数组。 I think that my function is correct by after filtered newArr is undefined . 我认为过滤后的newArr undefined后,我的功能是正确的。 Could you explain what is incorrect? 您能解释什么不正确吗?

var filterKey = 123456,
var array = [{ 
              ratings:{ users:[id: 123456]}, user: xyz
             },
             {
              ratings:{users:[id:9787389023]}, user:zyx
            }],

And my filter function 还有我的过滤功能

var newArr = array.forEach((ele) =>
                ele.ratings.users.filter((newEl) =>
                    newEl.id == filterKey))

Use array.filter method 使用array.filter方法

 let array = [ { id: 123456, user: 'xyz' }, { id:9787389023, user: 'zyx' }, { id: 123456, user: 'che' } ] let newArray = array.filter((element) => element.id === 123456) console.log(newArray) 

Use .filter and you'll be able to filter your result set without using foreach since it'll loop across the array. 使用.filter,您将无需使用foreach就可以过滤结果集,因为它会遍历整个数组。

 var find = 123456; var arr = [ { id: 123456, user: 'john' }, { id: 9787389023, user: 'leah' } ]; var results = arr.filter(function(node) { return node.id === find; }); console.log(results); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM