比较两个对象数组并删除第二个对象数组中具有相同属性值的项目 [英] Compare two arrays of objects and remove items in the second one that have the same property value

查看:20
本文介绍了比较两个对象数组并删除第二个对象数组中具有相同属性值的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做的就是比较两个对象数组并删除第二个对象中具有相同属性值的项目.例如:

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

我期望的是 b 中的以下内容:

What I expected was the following content in b:

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

推荐答案

FIDDLE

 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;
            }
        }
    }

这篇关于比较两个对象数组并删除第二个对象数组中具有相同属性值的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆