【发布时间】:2020-10-15 10:19:22
【问题描述】:
我正在尝试将 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",
}
];
【问题讨论】:
标签: javascript arrays sorting object