如果值不存在,需要将数组对象(arr1) valeus 压入另一个数组对象(arr2)。现有值不会插入另一个数组。
var arr1 = [{
name: 'fred'
}, {
name: 'bill'
}, {
name: 'ted'
}, {
name: 'james'
}];
var arr2 = [{
name: 'spil'
}, {
name: 'fred'
}, {
name: 'bill'
},{
name: 'paul'
}, {
name: 'stone'
}];
function add(name) {
var found = arr1.some(function (el) {
return el.name === name;
});
if (!found) {
arr1.push(arr2);
}
return arr2;
}
最佳答案
如果名称属性已经在 arr1
中,您可以使用哈希表进行查找。如果没有将实际项目推送到 arr1
。
var arr1 = [{ name: 'fred' }, { name: 'bill' }, { name: 'ted' }, { name: 'james' }],
arr2 = [{ name: 'toString' }, { name: 'spil' }, { name: 'fred' }, { name: 'bill' }, { name: 'paul' }, { name: 'stone' }],
hash = Object.create(null);
arr1.forEach(function (a) {
hash[a.name] = true;
});
arr2.forEach(function (a) {
hash[a.name] || arr1.push(a);
});
console.log(arr1);
附言
澄清一下,为什么 Object.create(null)
是一个像散列一样的真正空对象,而不是 {}
,一个空对象。注意 { name: 'toString' }
项。在第一部分,项目被插入,在第二部分没有,因为 hash
有一个名为 toString
的属性。
var arr1 = [{ name: 'fred' }, { name: 'bill' }, { name: 'ted' }, { name: 'james' }],
arr2 = [{ name: 'toString' }, { name: 'spil' }, { name: 'fred' }, { name: 'bill' }, { name: 'paul' }, { name: 'stone' }],
hash = {}; // now an object
arr1.forEach(function (a) {
hash[a.name] = true;
});
arr2.forEach(function (a) {
hash[a.name] || arr1.push(a);
});
console.log(arr1);
关于javascript - 如果值不存在,则将数组对象插入另一个数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38068424/