I'm new to JS and React and I'm a little stuck here. I've searched through SO but I'm having trouble finding a solution with an explanation that works.
Here are my arrays.
The first array is pretty simple.
[1, 3, 4,]
The second looks like this.
[
{
id: 1,
title: Title 1,
},
{
id: 2,
title: Title 2,
},
]
What I'd like to do is search the second array and if I can find an id that matches a value in the first array, add the object from the second array to third, new array.
I've tried a number of things and I'm sure there's a relatively easy way to do this with a forEach loop or lodash but I'm coming up blank.
Any help and explanations would be greatly appreciated.
Thanks,
Your second array is not valid. You have to wrap the string values with quotes.
You can use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes()
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Try the following way:
var arr1 = [1, 3, 4,];
var arr2 = [
{
id: 1,
title: 'Title 1',
},
{
id: 2,
title: 'Title 2',
},
];
var res = arr2.filter(i => arr1.includes(i.id));
console.log(res);
来源:https://stackoverflow.com/questions/51462062/loop-through-array-of-objects-check-for-a-matching-parameter-and-add-the-matchi