繁体   English   中英

如何添加或更新数组元素的属性:Javascript

[英]how can i add or update the property of an element of an array : Javascript

假设我们有一个具有 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",
   }
   ]

创建了一个 function,它可以首先检查 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",
    }
    ]

您可以使用map扩展语法轻松实现此结果

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

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

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

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

注意:此方法通过为O(1)恒定时间查找构建 map 来避免嵌套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);

暂无
暂无

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

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