繁体   English   中英

通过比较和推送唯一对象来获得新的对象数组

[英]New array of objects by comparing and pushing unique objects

我有2个对象excludepeople ,我想创建一个新对象,方法是检查people属性的exclude属性,只在不包含exclude功能的people添加对象。 到目前为止,我的尝试有点疯狂,并想知道是否有人可以帮助使事情变得更好或提供更好的解决方案?

小提琴 http://jsfiddle.net/kyllle/k02jw2j0/

JS

var exclude = [{
    id: 1,
    name: 'John'
}];

var peopleArr = [{
    id: 1,
    name: 'John'
}, {
    id: 2,
    name: 'James'
}, {
    id: 3,
    name: 'Simon'
}];

var myObj = [];
for (key in peopleArr) {
    for (k in exclude) {

        if (JSON.stringify(peopleArr[key]) != JSON.stringify(exclude[k])) {

            console.log(peopleArr[key]);
            myObj.push(peopleArr[key]);

        }
    }
}

console.log(myObj);

您重复一些JSON.stringify调用。
您可以将数组转换为JSON一次,然后重复使用它。 此外,您可以通过Array.prototype.filter替换您的push

var excludeJson = exclude.map(JSON.stringify);

peopleArr = peopleArr.filter(function(x) { 
    return excludeJson.indexOf(JSON.stringify(x)) === -1;
});

这是工作片段:

 var exclude = [{ id: 1, name: 'John' }]; var peopleArr = [{ id: 1, name: 'John' }, { id: 2, name: 'James' }, { id: 3, name: 'Simon' }]; var excludeJson = exclude.map(JSON.stringify); peopleArr = peopleArr.filter(function(x) { return excludeJson.indexOf(JSON.stringify(x)) === -1; }); document.body.innerText = JSON.stringify(peopleArr); 

这可以通过.filter.findIndex来实现

var myObj = peopleArr.filter(function(person){
   var idx = exclude.findIndex(function(exc) { return person.id == exc.id && person.name == exc.name; });
   return idx == -1; // means current person not found in the exclude list
});

我已经明确地将实际属性与原始属性进行了比较,你比较字符串化版本的原始方式没有什么特别的错误( JSON.stringify(e) == JSON.stringify(x)可以在我的例子中使用)

假设exclude可以有多个项目,我会使用filter()forEach()

var newArray = peopleArr.filter(function(person) {
    include = true;
    exclude.forEach(function(exl) {
        if (JSON.stringify(exl) == JSON.stringify(person)) {
            include = false;
            return;
        }
    })
    if (include) return person;
})

分叉小提琴 - > http://jsfiddle.net/6c24rte8/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM