简体   繁体   中英

Filter array items using forEach

I have one question about filter array in forEach. So I would like filter (bigger than in example) array using outside variable filterKey . I think that my function is correct by after filtered newArr is 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

 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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