gpt4 book ai didi

javascript - 如何使用javascript以优化方式将json一个结构解析为另一种结构?

转载 作者:行者123 更新时间:2023-12-01 15:34:26 24 4
gpt4 key购买 nike

我有以下json

let result = [
{
"category": "Social Media",
"category_id": 6,
"sub_category": "Facebook",
"sub_category_id": 5
},
{
"category": "Social Media",
"category_id": 6,
"sub_category": "Instagram",
"sub_category_id": 7
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Angular",
"sub_category_id": 1
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Javascript",
"sub_category_id": 6
}
]
我正在尝试在下面事件
[
{
"category": "Social Media",
"category_id": 6,
"sub_category": [
{
"sub_category": "Instagram",
"sub_catgory_id": 7
},
{
"sub_category": "Facebook",
"sub_catgory_id": 5
}
]
},
{
"category": "Tech",
"category_id": 3,
"sub_category": [
{
"sub_category": "Angular",
"sub_catgory_id": 1
},
{
"sub_category": "Javascript",
"sub_catgory_id": 6
}
]
}
]
下面的代码我试过了。谁能帮我确定我做错了什么?

let result = [{
"category": "Social Media",
"category_id": 6,
"sub_category": "Facebook",
"sub_category_id": 5
},
{
"category": "Social Media",
"category_id": 6,
"sub_category": "Instagram",
"sub_category_id": 7
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Angular",
"sub_category_id": 1
},
{
"category": "Tech",
"category_id": 3,
"sub_category": "Javascript",
"sub_category_id": 6
}
];

const dataArr = [];
result.forEach((value, key) => {
let catgeory = {
category: value.category,
category_id: value.category_id,
sub_category: []
};

catgeory.sub_category.push({
sub_category: value.sub_category,
sub_category_id: value.sub_category_id
})

dataArr.push(catgeory);
});

console.log(dataArr);

最佳答案

解释在评论中。

const data = {}

let result = [{"category":"Social Media","category_id":6,"sub_category":"Facebook","sub_category_id":5},{"category":"Social Media","category_id":6,"sub_category":"Instagram","sub_category_id":7},{"category":"Tech","category_id":3,"sub_category":"Angular","sub_category_id":1},{"category":"Tech","category_id":3,"sub_category":"Javascript","sub_category_id":6}];

// loop over each records
result.forEach((value) => {
// data will be object with key as category and value as category, category_id & sub_category array.
// get data[value.category], if not exist then create new object and assign.
data[value.category] = data[value.category] || {
category: value.category,
category_id: value.category_id,
sub_category: []
};
// push sub_category values.
data[value.category].sub_category.push({
sub_category: value.sub_category,
sub_category_id: value.sub_category_id
});
});

// we need array of values only so use Object.values(data)
let dataArr = Object.values(data);
console.log(dataArr);

关于javascript - 如何使用javascript以优化方式将json一个结构解析为另一种结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63485425/

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