我想要创造一个目的阵列从平面阵列,我将得到自的查询结果和想要创造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列的对象映射。 我已经尝试过这种代码,但coudnt实现预期产出。:
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);