gpt4 book ai didi

javascript - 合并相同 key 的 JSON 数据

转载 作者:行者123 更新时间:2023-11-28 15:17:40 24 4
gpt4 key购买 nike

嗨,我有一个 JSON 数据格式,如下所示维生素、menrals,我需要将相同的 json 键数组合并到单个数组中,

[
{
Vitamins: [
"Please explain details about vitamins.",
"Vitamin is a vitamin.:P:D",
"7"
]
},
{
Vitamins: [
"i need more explanation about VitaminD. bcoz i'm new to medicine field ",
"i don't know the ans.. :P",
"7"
]
},
{
Minerals: [
"i need more info about Minerals!",
"Minerals are found in soils",
"8"
]
}
]

但我需要更改为,请帮助如何合并它

[
{
Vitamins: [
{
"Please explain details about vitamins.",
"Vitamin is a vitamin.:P:D",
"7"
},
{
"i need more explanation about VitaminD. bcoz i'm new to medicine field ",
"i don't know the ans.. :P",
"7"
}
]
},
{
Minerals: [
"i need more info about Minerals!",
"Minerals are found in soils",
"8"
]
}
]

感谢任何帮助,提前致谢。

最佳答案

使用简单的foreach循环:

first = [
{
Vitamins: [
"Please explain details about vitamins.",
"Vitamin is a vitamin.:P:D",
"7"
]
},
{
Vitamins: [
"i need more explanation about VitaminD. bcoz i'm new to medicine field ",
"i don't know the ans.. :P",
"7"
]
},
{
Minerals: [
"i need more info about Minerals!",
"Minerals are found in soils",
"8"
]
}
];
last = {};
for (var i in first) {
if (typeof last[i] == "undefined")
last[i] = [];
last[i].push(first[i]);
}
console.log(last);

检查 JSBin 示例中的控制台。

JSBin:http://jsbin.com/guruxesaco/edit?js,console

关于javascript - 合并相同 key 的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32950528/

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