【问题标题】:how can i add or update the property of an element of an array : Javascript如何添加或更新数组元素的属性:Javascript
【发布时间】:2021-08-19 07:37:01
【问题描述】:

假设我们有一个具有属性 id、name、age 的数组。如果它不在现有数组中,我想向它添加更多属性,例如高度。如果该属性存在,它应该更新数组元素。

let array1 = [
    {
    id : 1,
    name : "Ravi",
    age : 29
    }
    {
    id : 2,
    name : "Nitin",
    age : 31,
    height : "5.5",
    }
    ]
let array2 = [
   {
   id : 1,
   height : "5.8",
   }
   {
   id : 2,
   height : "6.1",
   }
   ]

创建了一个函数,该函数可以首先检查 ID 是否存在,如果不存在则更新属性,然后创建它。 之后,它应该检查该属性是否存在,如果不存在则应该更新该属性,然后需要将属性添加到具有旧属性的现有元素中。

updateorinsert(array, item) { 
            const i = array.findIndex(_item => _item.id === item.id);
            if (i !== -1) { 
               array[i] = item; 
                array.map((element, index) => {
                    let result = array[index].hasOwnProperty("height");   
                    if(result == true){
                        // update the property
                    }else{
                        // add that property
                    }
                });               
            }
            else { 
                array.push(item);              
            }
        }
//Calling the function :

updateorinsert(array1, {id : 1, height : "5.8",}) // this can be changes as {id : 2, height : "6.1",} 
output_array = [
    {
    id : 1,
    name : "Ravi",
    age : 29,
    height : "5.8",
    },
    {
    id : 2,
    name : "Nitin",
    age : 31,
    height : "6.1",
    }
    ]

【问题讨论】:

  • 你试过什么?您能否更新您的问题以包含Minimal, Complete, and Reproducible Code Example
  • 我看到这里有2个数组,所以你想合并它们吗?
  • array1.map((o) => ({ ...o, ...array2.find((obj) => obj.id === o.id) }));
  • @Shyam - 看起来像那样。根据 id 获取高度,并将其添加到原始数组中。
  • 已经回答了。看看这个。如果不是那么请告诉我你还想要什么

标签: javascript arrays reactjs object multidimensional-array


【解决方案1】:

您可以使用mapspread syntax 轻松实现此结果

let array1 = [
  { id: 1, name: "Ravi", age: 29 },
  { id: 2, name: "Nitin", age: 31, height: "5.5" },
];

let array2 = [
  { id: 1, height: "5.8" },
  { id: 2, height: "6.1" },
];

const result = array1.map((o) => ({
  ...o,
  ...array2.find((obj) => obj.id === o.id),
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    如果您真正想做的只是合并数组并在以后看到任何值时覆盖任何值,那么确实没有必要专门计算是否需要插入或添加值。

    您可以将所有数组放入一个数组中,然后将它们缩减为一个数组。首先通过 id 创建一个映射到元素值,然后返回计算值数组。

    这里的想法是不断传播与id 属性匹配的值,如果该属性以前不存在,它现在会存在,如果存在,它将被覆盖。

    注意:此方法通过为O(1) 恒定时间查找构建映射,避免了嵌套array.findO(n) id 搜索复杂性。

    Object.values([/* ...arrays */].reduce((res, current) => {
      current.forEach(el => {
        res[el.id] = { ...res[el.id], ...el };
      });
      return res;
    }, {}));
    

    const array1 = [
      { id: 1, name: "Ravi", age: 29 },
      { id: 2, name: "Nitin", age: 31, height: "5.5" },
    ];
    const array2 = [
      { id: 1, height: "5.8" },
      { id: 2, height: "6.1" },
    ];
    
    const res = Object.values([array1, array2].reduce((res, current) => {
      current.forEach(el => {
        res[el.id] = { ...res[el.id], ...el };
      });
      return res;
    }, {}));
    
    console.log(res);

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 2012-09-04
      • 2014-12-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多