判断两个数组值一样删除一边的一个_比较两个对象数组,并删除第二个对象数组中具有相同属性值的项...

bd96500e110b49cbb3cd949968f18be7.png

All I need to do is compare two arrays of objects and remove items in the second one that have the same property value. For example:

var a = [{'name':'bob', 'age':22}, {'name':'alice', 'age':12}, {'name':'mike', 'age':13}];

var b = [{'name':'bob', 'age':62}, {'name':'kevin', 'age':32}, {'name':'alice', 'age':32}];

function remove_duplicates(a, b) {

for (var i = 0, len = a.length; i < len; i++) {

for (var j = 0, len = b.length; j < len; j++) {

if (a[i].name == b[j].name) {

b.splice(j, 1);

}

}

}

console.log(a);

console.log(b);

}

console.log(a);

console.log(b);

remove_duplicates(a,b);

I cannot understand why this does not work and instead gives:

Uncaught TypeError: Cannot read property 'name' of undefined

What I expected was the following content in b:

[{'name':'kevin', 'age':32}];

解决方案for (var i = 0, len = a.length; i < len; i++) {

for (var j = 0, len2 = b.length; j < len2; j++) {

if (a[i].name === b[j].name) {

b.splice(j, 1);

len2=b.length;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值