如何检查带有id的对象数组中是否存在id(在id列表中)?

时间:2016-03-29 15:21:33

标签: javascript node.js

的List1:

[1,2,3,4]

列表2:

[{id:1,name:hi},{id:3,name:hi},{id:5,name:hi}]

如何查看List2中缺少List1中的哪些项目?

5 个答案:

答案 0 :(得分:2)

您可以在 map() filter()

的帮助下做同样的事情



var list1 = [1, 2, 3, 4],
  list2 = [{
    id: 1,
    name: 'hi'
  }, {
    id: 3,
    name: 'hi'
  }, {
    id: 5,
    name: 'hi'
  }];

// get array of id's
var ids = list2.map(function(v) {
  return v.id;
})

// get missing elements
var miss = list1.filter(function(v) {
  // check element in id's array
  return ids.indexOf(v) == -1;
});

document.write('<pre>' + JSON.stringify(miss, null, 3) + '</pre>');
&#13;
&#13;
&#13;

使用ES6箭头功能

&#13;
&#13;
var list1 = [1, 2, 3, 4],
  list2 = [{
    id: 1,
    name: 'hi'
  }, {
    id: 3,
    name: 'hi'
  }, {
    id: 5,
    name: 'hi'
  }];

// get array of id's
var ids = list2.map(v => v.id);

// get missing elements
var miss = list1.filter(v => ids.indexOf(v) == -1);

document.write('<pre>' + JSON.stringify(miss, null, 3) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用Array.prototype.filter

var list1 = [1,2,3,4];
var list2 = [{id:1,name:'hi'},{id:3,name:'hi'},{id:5,name:'hi'}];

var t = list2.map(e => e.id); // get all 'ids' from 'list2'

var result = list1.filter(e => t.indexOf(e) == -1);

document.write(JSON.stringify(result));

答案 2 :(得分:1)

我会尝试将list2减少为缺少id的数组。也许是这样的:

var data = [{id: 1, name: 'hi'}, {id: 3, name: 'hi'}, {id: 5, name: 'hi'}]
var ids = [1, 2, 3, 4]

var missing = data.reduce(function(prev, curr) {
  return prev.filter(function(id) { return id !== curr.id })
}, ids.slice())

document.write(missing)

答案 3 :(得分:1)

对于排序数组具有线性复杂度的解决方案。

var list1 = [1, 2, 4, 30],
    list2 = [{ id: 1, name: 'hi' }, { id: 3, name: 'hi' }, { id: 5, name: 'hi' }],
    missing = list1.filter(function (a) {
        while (list2[this.index] && list2[this.index].id < a) {
            this.index++;
        }
        return !list2[this.index] || list2[this.index].id !== a;
    }, { index: 0 });

document.write('<pre>' + JSON.stringify(missing, 0, 4) + '</pre>');

答案 4 :(得分:1)

组合数组方法filtersome

var list1 = [1,2,3,4];
var list2 = [{id:1,name:'hi'},{id:3,name:'hi'},{id:5,name:'hi'}];
return list2.filter(function(o) {
    return !list1.some(function(id) { return o.id === id; })
})

产生来自list2的对象,其中的ID不在list1

正如我看到很多人发帖的那样,反过来说:

return list1.filter(function(id) {
     return !list2.some(function(o) { return o.id === id; });
});

list1

中生成list2中没有相应对象的ID