簡體   English   中英

從對象數組中添加/替換對象JavaScript

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

我想通過對array object測試一些propertiesobject array of objects添加/替換array object

  • object if name and id matches替換object if name and id matches

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

我正在使用下面的代碼,它的工作正常,但我不確定這是一個好的解決方案。

 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) 

您可以查找索引並更新數組(如果找到)或推送對象。

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

您可以使用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) 

在函數中包裝@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