gpt4 book ai didi

javascript - 将Json转换为父子关系结构

转载 作者:搜寻专家 更新时间:2023-11-01 05:27:16 25 4
gpt4 key购买 nike

想将 JSON 转换为父子关系。 Json 由 category 和 sub category 组成,匹配 Category 并将 subCategory 作为 child 插入其中

JSON

    [  {
"id": 0,
"category": "Business Services",
"subCategory": "Printing Services",
"isChecked": false
},
{
"id": 1,
"category": "Business Services",
"subCategory": "Waste Management Service",
"isChecked": false
},
{
"id": 2,
"category": "Consumer Products Manufacture - Food and Beverage",
"subCategory": "Alcoholic beverages",
"isChecked": false
},
{
"id": 3,
"category": "Consumer Products Manufacture - Food and Beverage",
"subCategory": "Cakes and Pastries",
"isChecked": false
},
{
"id": 4,
"category": "Finance",
"subCategory": "Finance Software and Services",
"isChecked": false
},
{
"id": 5,
"category": "Finance",
"subCategory": "Insurance",
"isChecked": false
},
]

想要从我拥有的原始 json 中得到以下 json 形式

       {category: 'Business Service',
[ {value:'Printing Service'},{value:'Waste Management
service'},..]
},
{ category :'Consumer products manufacture -Food and Beverage',
[{..}...]
}

最佳答案

您可以尝试减少您的输入数组并像这样简单地对您的输出进行排序:

const input = [{
"id": 0,
"category": "Business Services",
"subCategory": "Printing Services",
"isChecked": false
},
{
"id": 1,
"category": "Business Services",
"subCategory": "Waste Management Service",
"isChecked": false
},
{
"id": 2,
"category": "Consumer Products Manufacture - Food and Beverage",
"subCategory": "Alcoholic beverages",
"isChecked": false
},
{
"id": 3,
"category": "Consumer Products Manufacture - Food and Beverage",
"subCategory": "Cakes and Pastries",
"isChecked": false
},
{
"id": 4,
"category": "Finance",
"subCategory": "Finance Software and Services",
"isChecked": false
},
{
"id": 5,
"category": "Finance",
"subCategory": "Insurance",
"isChecked": false
},
]

const output = input.reduce((acc, cur) => {
if (typeof acc[cur.category] == "undefined")
acc[cur.category] = []
acc[cur.category].push({
value: cur.subCategory
});
return acc;
}, {})

console.log(output)

关于javascript - 将Json转换为父子关系结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57920142/

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