【发布时间】: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