【问题标题】:Filter array object by array object with a specific property按具有特定属性的数组对象过滤数组对象
【发布时间】:2020-06-29 15:58:25
【问题描述】:
const arr1 = [
  {id: 1, name: 'first'},
  {id: 2, name: 'second'},
  {id: 3, name: 'third'}
];
const arr2 = [
  {id: 1, name: 'first', color: 'blue'},
  {id: 2, name: 'second', color: 'red'}
];

我想按idarr2 的属性过滤arr1

结果应该是

result = [{id: 3, name: 'third}]

我试过了:

const arr1 = [
  {id: 1, name: 'first'},
  {id: 2, name: 'second'},
  {id: 3, name: 'third'}
];
const arr2 = [
  {id: 1, name: 'first', color: 'blue'},
  {id: 2, name: 'second', color: 'red'}
];
const result = arr1.filter((item) => {
  return arr2.some((value) => {
    return value.id !== item.id
  })
});
console.log(result);

但它的结果是

[
  {id: 1, name: 'first'},
  {id: 2, name: 'second'},
  {id: 3, name: 'third'}
];

我认为我的逻辑几乎是正确的。

有人可以帮忙解决这个简单的错误吗?

【问题讨论】:

    标签: javascript arrays filter


    【解决方案1】:

    使用这种方法,您需要寻找相同性并在查找时排除。

    const
        arr1 = [{ id: 1, name: 'first' }, { id: 2, name: 'second' }, { id: 3, name: 'third' }],
        arr2 = [{ id: 1, name: 'first', color: 'blue' }, { id: 2, name: 'second', color: 'red' }],
        result = arr1.filter(item => !arr2.some(value => value.id === item.id));
        //                           ^                            ^^^^
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2017-05-25
      • 1970-01-01
      • 2019-05-04
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多