gpt4 book ai didi

javascript - 映射键值以使用 javascript 创建具有嵌套对象的 json 结构

转载 作者:行者123 更新时间:2023-12-05 03:34:46 24 4
gpt4 key购买 nike

我想从我将从查询结果中获取的平面数组创建一个数组对象,并想创建 json 结构作为响应以将其作为 api 响应传递。例如-平面阵列-

[{
user_id: '2311123',
user_country: 'United States',
user_city: 'ny',
ssn: 229
},
{
user_id: '451313',
user_country: 'United States',
user_city: 'abc',
ssn: 147
},
{
user_id: '65345',
user_country: 'United States',
user_city: 'abc',
ssn: 444
},
{
user_id: '763343',
user_country: 'Australia',
user_city: 'auus',
ssn: 678
}]

我想创建一个类似预期输出的结构

{
"United States": [
{
"ny": [
{
"user_id": "2311123",
"ssn": "7"
}
]
},
{
"abc": [
{
"user_id": "451313",
"ssn": "147"
},
{
"user_id": "65345",
"ssn": "444"
}
]
}
],
"Australia": [
{
"auus": [
{
"user_id": "763343",
"ssn": "678"
}
]
}
]
}

其中映射了 user_country 对象数组和 user_city 对象数组。我试过这段代码,但无法达到预期的输出。:

  const map = {};
results.forEach(arr => {
console.log("arr",arr)
if(map[arr.user_country]){
if(!map[arr.user_country].includes(arr.user_city))
map[arr.user_country].push(arr.user_city);
}else{
map[arr.user_country] = [arr.user_city]
}
});
console.log(map);

最佳答案

这可能会产生预期的结果:

const array = [{ user_id: '2311123', user_country: 'United States', user_city: 'ny', ssn: 229 }, { user_id: '451313', user_country: 'United States', user_city: 'abc', ssn: 147 }, { user_id: '65345', user_country: 'United States', user_city: 'abc', ssn: 444 }, { user_id: '763343', user_country: 'Australia', user_city: 'auus', ssn: 678 }];


const map = array.reduce((map, {user_country, user_city, ...userInfo}) => {
if (!map[user_country]) {
map[user_country] = [{[user_city]: [{...userInfo}]}];
} else {
const ex = map[user_country].find(city => Object.keys(city)[0] === user_city);
if (!ex) {
map[user_country].push({[user_city]: [{...userInfo}]});
} else {
Object.values(ex)[0].push({...userInfo});
}
}
return map;
}, {});

console.log(map);

关于javascript - 映射键值以使用 javascript 创建具有嵌套对象的 json 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70091457/

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