gpt4 book ai didi

javascript - 将类似的 JSON 对象分组到数组中

转载 作者:行者123 更新时间:2023-11-30 11:42:35 24 4
gpt4 key购买 nike

我有一个库返回的模型,格式如下:

var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}]

如何将“fName”组合在一起并添加“[]”以获得:

{ 'fName[]': ['john','mike'],'country[]': ['USA'] };

**注意 countryfName 完全不相关。

最佳答案

建议(使用ES6语法)

const transformData = (data) => {
const newData = {}
data.forEach( (item) => {
for (let key in item) {
const newKey = key + "[]"
if (!newData.hasOwnProperty(newKey)) newData[newKey] = []
newData[newKey].push(item[key])
}
})
return newData
}

/* added some extra keys just to test */
let givenData = [
{"fName": "john", "country": "England"},
{"fName": "mike"},
{"country": "USA"},
{"language": "English"}
]

console.log(transformData(givenData))
/*
{
"fName[]": ["john","mike"],
"country[]": ["England","USA"],
"language[]":["English"]
}
*/

关于javascript - 将类似的 JSON 对象分组到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42077841/

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