如果数组中不存在值,我该如何对对象数组进行操作,如果必须存在,则必须将其推入该数组;如果存在,则不能将其推入该数组

时间:2019-05-14 06:37:42

标签: javascript reactjs

如何避免数组中的重复对象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

1 个答案:

答案 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);