简体   繁体   English

从对象数组中添加/替换对象JavaScript

[英]Add/Replace object from array of objects JavaScript

I want to Add/Replace the object from array of objects by testing some properties against array object 我想通过对array object测试一些propertiesobject array of objects添加/替换array object

  • Replace object if name and id matches object if name and id matches替换object if name and id matches

  • Add object to the array if name and id does not match from array objects array if name and id does not match from array objects object添加到array if name and id does not match from array objects

I am using below code, its working fine but I am not sure is it a good solution. 我正在使用下面的代码,它的工作正常,但我不确定这是一个好的解决方案。

 let arr = [{name: 'test1', id:1, data: {a:1} }, {name:'test2', id:2, data: {a:2}}] let obj = {name:'test3', id:3, data: {a:3}} let itemFound = false; let newArr = arr.map((item)=>{ let test = item.name === obj.name && item.id === obj.id; if(test){ itemFound = true; } return test ? obj : item; }); if(!itemFound){ newArr.push(obj); } console.log(newArr) 

You could look for the index and update the array, if found or push the object. 您可以查找索引并更新数组(如果找到)或推送对象。

 var array = [{ name: 'test1', id: 1, data: { a: 1 } }, { name: 'test2', id: 2, data: { a: 2 } }], object = { name: 'test3', id: 3, data: { a: 3 } }, index = array.findIndex(({ name, id }) => name === object.name && id === object.id); if (index === -1) { array.push(object); } else { array[index] = object; } console.log(array); 

You can use Array.prototype.find() 您可以使用Array.prototype.find()

 let arr = [{name: 'test1', id:1, data: {a:1} }, {name:'test2', id:2, data: {a:2}}] let obj = {name:'test3', id:3, data: {a:3}} const newArr = arr.slice(); const existingObj = newArr.find(item => item.name === obj.name && item.id === obj.id); if(existingObj) { Object.assign(existingObj, obj); } else { newArr.push(obj) } console.log(newArr) 

Wraping @Nina Scholz 's answer in a function 在函数中包装@Nina Scholz的答案


objectReplacer(arrayOfObjects, newObject) {

      let index = arrayOfObjects.findIndex((value) => value === newObject.value);

      if (index === -1) {
        arrayOfObjects.push(newObject);
      } else {
        arrayOfObjects[index] = newObject;
      }
    }

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

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