gpt4 book ai didi

javascript - 组合具有相同值的对象数组中的对象

转载 作者:行者123 更新时间:2023-11-30 19:12:35 25 4
gpt4 key购买 nike

这是一个包含类别的对象数组以及每个类别所属的解决方案。解决方案是重复的,但类别是唯一的。

const categories = [
{ category: 'Patch Leads', solution: 'Data Solutions' },
{ category: 'Cables', solution: 'Data Solutions' },

{ category: 'Nails', solution: 'Hardware' },
{ category: 'Locks', solution: 'Hardware' },
{ category: 'Screws', solution: 'Hardware' },

{ category: 'Cabinets', solution: 'Cabinet Solutions' },
{ category: 'Swing Frames', solution: 'Cabinet Solutions' },
{ category: 'Racks', solution: 'Cabinet Solutions' },

{ category: 'Fire Cables', solution: 'Fire Solutions' },

];

我需要返回一个新的解决方案对象数组。这是最终结果的格式。当像 ID 的索引一样循环时,获取此格式的所有数据都可用,但我无法正确获取我的代码格式。

const solutions = [
{
id: "0",
name: "Data Solutions",
categories: [
{
id: "0",
name: "Cables",
slug: "cables"
},
{
id: "1",
name: "Patch Leads",
slug: "patch-leads"
}
]
},
{
id: "1",
name: "Hardware",
categories: [
{
id: "0",
name: "Nails",
slug: "nails"
},
{
id: "1",
name: "Locks",
slug: "locks"
},
{
id: "2",
name: "Screws",
slug: "screws"
}
]
},
{
id: "2",
name: "Cabinet Solutions",
categories: [
{
id: "0",
name: "Cabinets",
slug: "cabinets"
},
{
id: "1",
name: "Swing Frames",
slug: "swing-frames"
},
{
id: "2",
name: "Racks",
slug: "racks"
}
]
},
{
id: "3",
name: "Fire Solutions",
categories: [
{
id: "0",
name: "Fire Cables",
slug: "gire-cables"
}
]
}
]

最佳答案

您可以使用 reduce()方法来做到这一点。迭代时,如果当前项目已经存在,则将当前类别附加到现有项目。如果没有,请使用当前类别创建一个新项目。

const categories = [ { category: 'Patch Leads', solution: 'Data Solutions' }, { category: 'Cables', solution: 'Data Solutions' }, { category: 'Nails', solution: 'Hardware' }, { category: 'Locks', solution: 'Hardware' }, { category: 'Screws', solution: 'Hardware' }, { category: 'Cabinets', solution: 'Cabinet Solutions' }, { category: 'Swing Frames', solution: 'Cabinet Solutions' }, { category: 'Racks', solution: 'Cabinet Solutions' }, { category: 'Fire Cables', solution: 'Fire Solutions' }, ];

var solutions = categories.reduce((acc, curr) => {
let item = acc.find(item => item.name === curr.solution);

if (item) {
item.categories.push({
"id": item.categories.length,
"name": curr.category,
"slug": curr.category.toLowerCase().replace(' ', '-')
});
} else {
acc.push({
"id": acc.length,
"name": curr.solution,
"categories": [{
"id": 0,
"name": curr.category,
"slug": curr.category.toLowerCase().replace(' ', '-')
}]
});
}

return acc;
}, []);

console.log(solutions);

关于javascript - 组合具有相同值的对象数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com