Javascript:将对象添加到具有相同键不起作用的对象现有数组中



我正在尝试将newList添加到Grouped数组中,其中Grouped数组名称与newList名称相同。例如,将"乳制品和鸡蛋"对象从newList连接到Grouped数组。这在所需的输出中得到了证明。

我尝试过的:

const existingCatrgory = Grouped.findIndex(
item => item.name === 'Spices' || 'Dairy and Eggs' || 'Produce'
);
if (existingCatrgory >= 0) {
const findShoppingCategory = Grouped.filter(x => x.name === 'Spices' || 'Dairy and Eggs' || 'Produce')
const merge = findShoppingCategory.map((element) => {
return {
...element,
data: element.data.concat(newList)
};
});
} else {
return Grouped.concat(newList)
}

这是newList

const newList = [{
data: [{
value: "whipped cream"
}, ],
name: "Dairy and Eggs",
},
{
data: [{
value: "mushrooms",
}],
name: "Produce",
}
]

这是Grouped Array

const Grouped = [{
data: [{
value: "paprika",
}, ],
name: "Spices",
},
{
data: [
{value: "milk"},
{value: "Blue cheese"},
],
name: "Dairy and Eggs",
},
];

期望输出:

const Output = [{
data: [
{ value: "paprika" },],
name: "Spices",
},
{
data: [
{ value: "milk" },
{ value: "Blue cheese" },
{ value: "whipped cream" },
],
name: "Dairy and Eggs"
},
{
data: [
{ value: "mushrooms" }
],
name: "Produce",
}
];

这里有一种方法可以做到这一点:

const Grouped = [{
data: [{
value: "paprika",
}, ],
name: "Spices"
},
{
data: [
{value: "milk"},
{value: "Blue cheese"},
],
name: "Dairy and Eggs"
},
];
const newList = [{
data: [{
value: "whipped cream"
}, ],
name: "Dairy and Eggs"
},
{
data: [{
value: "mushrooms",
}],
name: "Produce"
}
]
const mergedList = JSON.parse(JSON.stringify(Grouped));
newList.forEach(function(item){
let thisGroup = mergedList.filter(g => g.name == item.name);
if (thisGroup.length > 0) {
for (let i = 0; i < item.data.length; i++) {
thisGroup[0].data.push({"value": item.data[i].value});
}
} else {
mergedList.push(item);
}
})
console.log(mergedList);

只需遍历每个新项目并检查名称是否已存在,如果存在,则将新的 data.value 附加到现有数据列表中。如果不存在,请为该项创建一个新条目。

根据要求,我更新了代码,以包括获取分组数组的副本并合并到该数组中。 由于分组数组的结构很简单,因此我使用 JSON 将其字符串化并解析回新数组。

这是另一种使用 findIndex 的解决方案,它可以创建新项或添加到现有数据。

newList.forEach(newItem =>{
let index = Grouped.findIndex(item => item.name ===newItem.name)
if(index===-1){
Grouped.push(newItem)
}else{
Grouped[index].data.push(...newItem.data)
}
})

最新更新