Loop through array of objects, check for a matching parameter and add the matching object to new array

耗尽温柔 提交于 2019-12-06 15:59:43

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!