遍历对象数组,检查匹配的参数并将匹配的对象添加到新数组 [英] Loop through array of objects, check for a matching parameter and add the matching object to new array

查看:476
本文介绍了遍历对象数组,检查匹配的参数并将匹配的对象添加到新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS和React的新手,但是我有点卡在这里.我已经搜索过SO,但是在找到有效解释的解决方案时遇到了麻烦.

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.

这是我的数组.

第一个数组非常简单.

[1, 3, 4,]

第二个看起来像这样.

[
  {
    id: 1,
    title: Title 1,
   },
  {
    id: 2,
    title: Title 2,
   },
]

我想做的是搜索第二个数组,如果我可以找到一个与第一个数组中的值匹配的id,则将第二个数组中的对象添加到第三个新数组中.

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.

我已经尝试了很多方法,并且我确定有一个相对简单的方法可以使用forEach循环或lodash来完成此操作,但是我将变得空白.

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.

谢谢

推荐答案

您的第二个数组无效.您必须用引号将字符串值引起来.

Your second array is not valid. You have to wrap the string values with quotes.

您可以使用 Array.prototype.filter()

You can use Array.prototype.filter()

filter()方法创建一个新数组,其中包含所有通过提供的功能实现的测试的元素.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.includes()

includes()方法确定数组是否包含某个元素,并在适当时返回true或false.

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

尝试以下方式:

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

这篇关于遍历对象数组,检查匹配的参数并将匹配的对象添加到新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆