比较两个obj数组中的值并从第一个数组中删除


var firstOne = [
    { id: 22, value: 'hi there' },
    { id: 28, value: 'here' },
    { id: 77, value: 'what' }
];
var secondOne = [
    { id: 2, value: 'bond' },
    { id: 8, value: 'foobar' },
    { id: 87, value: 'what' }
];

我正在寻找按值比较两个对象数组的最佳方法。如果两者中的value相同,则从firststone中删除它,这将导致:

var firstOne = [
    { id: 22, value: 'hi there' },
    { id: 28, value: 'here' }
];
var secondOne = [
    { id: 2, value: 'bond' },
    { id: 8, value: 'foobar' },
    { id: 87, value: 'what' }
];

Javascript或Angular解决方案将受到赞赏。由于

您可以使用Set进行过滤。

var firstOne = [{ id: 22, value: 'hi there' }, { id: 28, value: 'here' }, { id: 77, value: 'what' }],
    secondOne = [{ id: 2, value: 'bond' }, { id: 8, value: 'foobar' }, { id: 87, value: 'what' }],
    mySet = new Set;
secondOne.forEach(function (a) {
    mySet.add(a.value);
});
firstOne = firstOne.filter(function (a) {
    return !mySet.has(a.value);
});
console.log(firstOne);

ES6

var firstOne = [{ id: 22, value: 'hi there' }, { id: 28, value: 'here' }, { id: 77, value: 'what' }],
    secondOne = [{ id: 2, value: 'bond' }, { id: 8, value: 'foobar' }, { id: 87, value: 'what' }],
    mySet = new Set;
secondOne.forEach(a => mySet.add(a.value));
firstOne = firstOne.filter(a => !mySet.has(a.value));
console.log(firstOne);

相关内容

最新更新