从2个对象数组中获取缺少的对象

时间:2017-02-03 16:49:41

标签: javascript ecmascript-6

let selected = [
  {id: 15, name: 'Canada'},
  {id: 25, name: 'Germany'}
];

let all = [
  {id: 15, name: 'Canada'},
  {id: 25, name: 'Germany'},
  {id: 32, name: 'United States'},
  {id: 40, name: 'China'}
]

如何从all个对象中获取未选择的国家/地区并将其打印在另一个变量中?基于id数组中的selected密钥?

3 个答案:

答案 0 :(得分:3)

您需要找到selected中未包含的所有对象,然后对它们执行某些操作:

let nonSelectedItems = all.filter(obj => selected.every(s => s.id !== obj.id));

//do stuff with non-selected items

答案 1 :(得分:1)

使用Array#reduce方法生成一个将id作为属性保存的对象(这有助于加速,因为您需要反复迭代)并使用Array#filter方法过滤来自{{1}的元素} array。

all



// generate the object reference
let ref = selected.reduce(function(obj, o) {
  // define property
  obj[o.id] = true;
  // return object property
  return obj;
  // set initial value as an object
}, {});

// filter out array elements
let res = all.filter(function(o) {
  return !ref[o.id]
})




使用ES6 arrow function

let selected = [{
  id: 15,
  name: 'Canada'
}, {
  id: 25,
  name: 'Germany'
}];

let all = [{
  id: 15,
  name: 'Canada'
}, {
  id: 25,
  name: 'Germany'
}, {
  id: 32,
  name: 'United States'
}, {
  id: 40,
  name: 'China'
}]

let ref = selected.reduce(function(obj, o) {
  obj[o.id] = true;
  return obj;
}, {});

console.log(
  all.filter(function(o) {
    return !ref[o.id]
  })
)



let ref = selected.reduce((obj, o) => (obj[o.id] = true, obj), {});

let res = all.filter(o => !ref[o.id]);




答案 2 :(得分:1)

您可以使用filterfind,因此只要在id中找到具有相同selected的元素,它就会从all过滤掉该元素。您也可以使用some代替find

let selected = [
  {id: 15, name: 'Canada'},
  {id: 25, name: 'Germany'}
];

let all = [
  {id: 15, name: 'Canada'},
  {id: 25, name: 'Germany'},
  {id: 32, name: 'United States'},
  {id: 40, name: 'China'}
]

var r = all.filter(e => !selected.find(a => e.id == a.id));
console.log(r)