gpt4 book ai didi

javascript - 在数组json中的单个对象中转换多个相同的键对象

转载 作者:行者123 更新时间:2023-11-29 23:04:19 30 4
gpt4 key购买 nike

我在下面有这个 json:

[
{"animal": "cat"},
{"animal": "dog"},
{"animal": "elephant"},
{"vehicle": "car"},
{"vehicle": "bike"},
{"vehicle": "truck"},
{"toys": "a1"},
{"toys": "a2"},
{"toys": "a3"}
]

我预期的 json 响应是:

[
{"animal": "cat", "vechile": "car", "toys": "a1"},
{"animal": "dog", "vechile": "bike", "toys": "a2"},
{"animal": "elephant", "vechile": "truck", "toys": "a3"}
]

我尝试了以下程序,但没有给我预期的输出,我想制作一个数组,以便我可以比较它并相应地添加:

var myGlobalArr = []
var globalObject = {}

for (var i = 0; i < mainArr.length; i++)
{
if (Object.keys(mainArr[i])[0] == Object.keys(myGlobalArr[i])[0])
{
globalObject[Object.keys(mainArr[i])[0]] = globalObject[Object.values(mainArr[i])[0]]
}
}

console.log(myGlobalArr)

不胜感激!!

#EDITED:

它将是 3 的 block 。

最佳答案

您可以使用 Array.reduce() 执行此操作.在 reduce 的每次迭代中,您可以检查最终数组的哪个索引使用对象的当前索引 modulus 3 (idx % 3):

const input = [
{"animal": "cat"},
{"animal": "dog"},
{"animal": "elephant"},
{"vehicle": "car"},
{"vehicle": "bike"},
{"vehicle": "truck"},
{"toys": "a1"},
{"toys": "a2"},
{"toys": "a3"}
];

let res = input.reduce((acc, curr, idx) =>
{
let [[k, v]] = Object.entries(curr);
acc[idx % 3] = acc[idx % 3] || {};
acc[idx % 3][k] = v;
return acc;
}, [])

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

关于javascript - 在数组json中的单个对象中转换多个相同的键对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55056883/

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