Javascript:将对象添加到具有相同键的现有对象数组中不起作用
我正在尝试将Javascript:将对象添加到具有相同键的现有对象数组中不起作用,javascript,arrays,sorting,object,Javascript,Arrays,Sorting,Object,我正在尝试将newList添加到Grouped数组中,其中Grouped数组名称与newList名称相同。例如,将“乳制品和鸡蛋”对象从newList集中到Grouped数组中。这在所需的输出中得到了证明 我所尝试的: const existingCatrgory = Grouped.findIndex( item => item.name === 'Spices' || 'Dairy and Eggs' || 'Produce' ); if (existingCatrgory
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)
}
这是新列表
:
const newList = [{
data: [{
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 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=[{
数据:[{
价值:“红辣椒”,
}, ],
名称:“香料”
},
{
数据:[
{值:“牛奶”},
{value:“蓝奶酪”},
],
名称:“乳制品和鸡蛋”
},
];
常数newList=[{
数据:[{
价值:“鲜奶油”
}, ],
名称:“乳制品和鸡蛋”
},
{
数据:[{
价值:“蘑菇”,
}],
名称:“生产”
}
]
const mergedList=JSON.parse(JSON.stringify(Grouped));
newList.forEach(函数(项){
让thisGroup=mergedList.filter(g=>g.name==item.name);
如果(thisGroup.length>0){
for(设i=0;i console.log(合并列表)代码>这里是另一个使用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)
}
})
哇,谢谢你的回答。你能让这个返回一个新的数组而不是改变状态吗?提前非常感谢!!!!np-我已经更新了我的答案,包括获取分组数组的副本,并与副本而不是原始数组合并。