如何避免数组中的重复对象push()?
let arrOj = [
{id: 1, name: 'foo', source: 234},
{id: 2, name: 'bar', source: 23 },
{id: 3, name: 'test', source: 4},
{id: 1, name: 'change', source: 234}
];
仅在name值不存在的情况下循环遍历此对象数组“ arrOj”,并将每个对象的值推入此新数组“ arrNew”中
let arrNew = [
{id: 1, name: 'foo', source: 234},
{id: 2, name: 'bar', source: 23 },
{id: 3, name: 'test', source: 4}
];
所以我只想在名称不存在的情况下将新值压入数组
{id: 1, name: 'change', source: 234}, // i can push this value
{id: 1, name: 'foo', source: 234}, // i must not push this value because the name does exists
答案 0 :(得分:0)
如果我理解得很好,应该这样做
let arrOj = [
{id: 1, name: 'foo', source: 234},
{id: 2, name: 'bar', source: 23 },
{id: 3, name: 'change', source: 234}
];
let arrNew = [
{id: 1, name: 'foo', source: 234},
{id: 2, name: 'bar', source: 23 },
{id: 3, name: 'test', source: 4}
];
function avoidDouble(newObj){
let found = false;
for(obj of arrOj){
if(obj.name == newObj.name){
found = true;
console.log("double found !");
break;
}
}
if(!found) arrOj.push(newObj);
}
for(item of arrNew) avoidDouble(item);
console.log(arrOj);