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))
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))
Share
Improve this question
edited Feb 13, 2018 at 17:56
Mat.Now
asked Feb 13, 2018 at 17:38
Mat.NowMat.Now
1,7353 gold badges19 silver badges31 bronze badges
6
-
3
.forEach()
doesn't return anything. You are probably looking for the actual.filter()
– VLAZ Commented Feb 13, 2018 at 17:40 -
1
Your
ele
ments in your examplearray
do not have a.rating.users
property that holds an array?! – Bergi Commented Feb 13, 2018 at 17:41 - Oh God, I forgot change array... sorry for messing – Mat.Now Commented Feb 13, 2018 at 17:57
-
id: 123456
is invalid syntax in an array literal. Did you mean to have a single object in each of the arrays? – Bergi Commented Feb 13, 2018 at 18:00 - What is the expected result? – Bergi Commented Feb 13, 2018 at 18:00
2 Answers
Reset to default 3Use 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);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744168865a4561435.html
评论列表(0条)