比较两个数组中的对象并根据javascript中的匹配返回 [英] Compare objects in two arrays and return based on match in javascript

查看:71
本文介绍了比较两个数组中的对象并根据javascript中的匹配返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React,但概念是在javascript中。因此,为了简单起见,我希望我可以保留React代码。

I am using React for this, but the concept is in javascript. So hopefully I can leave React code out for simplicity sake.

我需要过滤掉两个数组。我的目标是映射数组并检查该对象的属性是否与另一个数组的对象中的属性匹配。

I have two arrays that I need to filter out. My goal is to map over an array and check if a property of that object matches a property in an object of the other array.

第一个数组如下所示:

[{id: 1}, {id: 2}, {id: 3}, {id: 4}]

秒一个看起来像这样:

[{id: 3}, {id: 4}]

因此,如果一个对象具有相同的 id 属性作为另一个数组中的对象,返回一个反应元素/任何东西。

So if one object has the same id property as an object in the other array, return a react element/anything.

这是我必须工作的东西,但它只通过索引并比较它们。这似乎在第一个数组上正确循环,但我似乎无法通过索引以外的任何东西遍历第二个数组。

Here is something I got to work, but it only goes through the index and compares them. This appears to loop over the 1st array properly, but I cant seem to loop over the second array by anything other than the index.

return arr1.map((e, i) => {
  return if (e.id === arr2[i].id) {
    return <div>Match</div>
  } else {
    return <div>No Match</div>
  }
})


推荐答案

您的问题是您在逐个索引进行比较。你想知道arr1中的元素是否在arr2中任何地方,对吗?

Your problem is you are comparing index-by-index. You want to know if the element in arr1 is anywhere in arr2, right?

我会用 arr2.filter 搜索所有arr2。所以你会有这样的事情:

I would use arr2.filter to search all of arr2. So you would have something like this:

return arr1.map((e1, i) => {
  if (arr2.filter(e2 => e2.id === e1.id).length > 0) {  // If there's a match
    return <div>Match</div>
  } else {
    return <div>No Match</div>
  }
})

更新:
根据评论中的建议使用 Array.some 在这里更好:

return arr1.map((e1, i) => {
  if (arr2.some(e2 => e2.id === e1.id)) {  // If there's a match
    return <div>Match</div>
  } else {
    return <div>No Match</div>
  }
})

这篇关于比较两个数组中的对象并根据javascript中的匹配返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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