gpt4 book ai didi

javascript - 如何根据key id合并Json对象?

转载 作者:太空宇宙 更新时间:2023-11-04 02:54:19 24 4
gpt4 key购买 nike

我有一个这样的json。现在我想根据articleId进行合并。

                   [{
"articleId": "45",
"isA": false,
"flags": {
"isDema": false,
"isCont": true,
},
"Proc": [
{
"level1": "tt",
"description": "I am well"
}
],
"isAlert": false
},
{
"articleId": "46",
"isA": false,
"flags": {
"isDema": false,
"isCont": true,
},
"Proc": [
{
"level1": "ty",
"description": "I am fine"
}
],
"isAlert": false
},
{
"articleId": "45",
"isA": false,
"flags": {
"isDema": false,
"isCont": true,
},
"Proc": [
{
"level1": "tt",
"description": "I am beautiful"
}
],
"isAlert": false
}];

我们在这里看到文章 ID 45 是两次,尽管描述字段不同。所以我想在一个数组中添加描述。合并后我想得到这样的输出。

[{
"articleId": "45",
"isA": false,
"flags": {
"isDema": false,
"isCont": true,
},
"Proc": [
{
"level1": "tt",
"description":[
"I am well",
"I am beautiful"
]
}
],
"isAlert": false
},
{
"articleId": "46",
"isA": false,
"flags": {
"isDema": false,
"isCont": true,
},
"Proc": [
{
"level1": "ty",
"description": "I am fine"
}
],
"isAlert": false
}];

我正在尝试直接字符串解析。还有其他办法吗?顺便说一句,我正在使用 Node.js。是否有任何内置方法可以合并两个 json 对象?

最佳答案

使用 map 按articleId分组,其中键是articleId:

const source = [{"articleId":"45","isA":false,"flags":{"isDema":false,"isCont":true},"Proc":[{"level1":"tt","description":"I am well"}],"isAlert":false},{"articleId":"46","isA":false,"flags":{"isDema":false,"isCont":true},"Proc":[{"level1":"ty","description":"I am fine"}],"isAlert":false},{"articleId":"45","isA":false,"flags":{"isDema":false,"isCont":true},"Proc":[{"level1":"tt","description":"I am beautiful"}],"isAlert":false}];

const bucket = {}
source.map((item) => {
const merged = bucket[item.articleId];
if (!merged) {
item.Proc[0].description = [item.Proc[0].description]
bucket[item.articleId] = item;
return;
}
merged.Proc[0].description.push(item.Proc[0].description)
});

const out = [];
for (const key in bucket) {
const val = bucket[key];
if (val.Proc[0].description.length === 1) {
val.Proc[0].description = val.Proc[0].description.pop();
}
out.push(val);
}

console.log(JSON.stringify(out));

关于javascript - 如何根据key id合并Json对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368097/

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