首页 > 解决方案 > 查找仅在 array1 javascript 中可用的对象

问题描述

这里我有两个数组。我想获取仅在 Array1 中可用的值。一些场景

  1. 如果两者都有共同的项目,则返回空。
  2. 如果两者都没有任何共同项目,则返回 array1 的所有项目。
  3. 如果 array1 有 item1 在数组 2 中不可用,则仅返回 item1

var Array1 = [{
    id : 1,
    name : 'item1'
}, {
    id : 2,
    name : 'item2'
}];
 var Array2 = [{
        id : 1,
        name : 'item1',
        expiredate : 2022
    },
    {   id : 3,
        name : 'item3',
        expiredate : 2022
    }
];

// now want a result array3 which contains the item only available in array1. for above examplle item2

标签: javascriptarraysarraylist

解决方案


你想要的只是array1array2-

var array1 = [{
  id: 1,
  name: 'item1'
}, {
  id: 2,
  name: 'item2'
}];
var array2 = [{
    id: 1,
    name: 'item1',
    expiredate: 2022
  },
  {
    id: 3,
    name: 'item3',
    expiredate: 2022
  }
];

var array3 = array1.filter(b =>
  !array2.some(s => s.id === b.id && s.name === b.name));

console.log(array3);


推荐阅读