[英]New array of objects by comparing and pushing unique objects
我有2个对象exclude
和people
,我想创建一个新对象,方法是检查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.