简体   繁体   English

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

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

Let's suppose we have an array that has properties id, name, age.假设我们有一个具有 id、name、age 属性的数组。 I want to add more properties to it like height if it is not in the existing array.如果它不在现有数组中,我想向它添加更多属性,例如高度。 And if it that property exists it should update the array element.如果该属性存在,它应该更新数组元素。

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",
   }
   ]

Created a function that could first check if ID exists then update the property if doesn't exists then create it.创建了一个 function,它可以首先检查 ID 是否存在,如果不存在则更新属性,然后创建它。 After that it should check it the property exists then it should update the property if not then property needs to be added to existing element having old properties.之后,它应该检查该属性是否存在,如果不存在则应该更新该属性,然后需要将属性添加到具有旧属性的现有元素中。

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",
    }
    ]

You can easily achieve this result using map and spread syntax您可以使用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; }

It's really unnecessary to specifically compute if a value needs to be inserted or added if all you really want to do is merge arrays and overwrite any value if it's seen later.如果您真正想要做的只是合并 arrays 并在以后看到任何值时覆盖任何值,那么实际上没有必要专门计算是否需要插入或添加一个值。

You can place all your arrays into an array and reduce them into a single array.您可以将所有 arrays 放入一个数组中,并将它们减少为一个数组。 First create a map by id to element values, then return the array of computed values.首先通过 id 到元素值创建一个 map,然后返回计算值数组。

The idea here is to continually spread in the values matched by the id property, if the property didn't exist previously it will now, and if it did it will be overwritten.这里的想法是不断地传播与id属性匹配的值,如果该属性以前不存在,它现在会存在,如果存在,它将被覆盖。

Note: This method avoids the O(n) id search complexity of the nested array.find by building a map for O(1) constant time lookups.注意:此方法通过为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