如何在 React 中合并两个列表?

How to merging two lists in React?

我需要有关在 ReactJs 中合并 2 个列表的帮助。 例如, 列表一:

[
{id:1,name:"abc",city:"ddd"},
{id:2,name:"cde",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
]

列表二:

[
{id:1,name:"abc"},
{id:3,name:"ttt"}
]

我想要得到的结果是

[
{id:1,name:"abc",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
]

最清楚的方法是什么?

你可以使用过滤器和一些数组方法。

 const arr1 = [
  {id:1,name:"abc",city:"ddd"},
  {id:2,name:"cde",city:"ddd"},
  {id:3,name:"ttt",city:"fff"}
];

const arr2 = [
  {id:1,name:"abc"},
  {id:3,name:"ttt"}
];


const filteredArray = arr1.filter((el) => {
  return arr2.some((x) => {
    return x.id === el.id && x.name === el.name;
  });
});

console.log(filteredArray);