我有两个对象数组:
array1 = [
{id:1, name: 'one'},
{id:4, name: 'four'}
]
array2 = [
{id:1, name: 'one'},
{id:2, name: 'two'},
{id:3, name: 'three'},
{id:5, name: 'five'},
{id:6, name: 'six'},
{id:7, name: 'seven'}
]
我想删除array1
中id
array2
不存在的array1 = [
{id:1, name:'one'}
]
中的任何对象。
所以我期望的结果是:
background-image: url('http://ekozone.local/src/img/logo.png');
答案 0 :(得分:2)
使用lodash的_.intersectionBy()
:
var array1 = [
{id:1, name: 'one'},
{id:4, name: 'four'}
];
array2 = [
{id:1, name: 'one'},
{id:2, name: 'two'},
{id:3, name: 'three'},
{id:5, name: 'five'},
{id:6, name: 'six'},
{id:7, name: 'seven'}
];
var result = _.intersectionBy(array1, array2, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
答案 1 :(得分:1)
快速可读的选项是:
{{1}}
但不能保证它在所有方面都是最快的。 (重复次数,array1的长度,array2的长度)。
答案 2 :(得分:0)
您可以使用标准方法,使用哈希表,只对一个阵列使用一次迭代。
var array1 = [{ id: 1, name: 'one' }, { id: 4, name: 'four' }],
array2 = [{ id: 1, name: 'one' }, { id: 2, name: 'two' }, { id: 3, name: 'three' }, { id: 5, name: 'five' }, { id: 6, name: 'six' }, { id: 7, name: 'seven' }],
hash = Object.create(null),
result;
array2.forEach(function (o) {
hash[o.id] = true;
});
result = array1.filter(function (o) {
return hash[o.id];
});
console.log(result);
答案 3 :(得分:0)
您可以使用Set
:
const seenIds = array2.reduce((set, o) => set.add(o.id), new Set());
const result = array1.filter(o => seenIds.has(o.id));