gpt4 book ai didi

javascript - 如何通过group by json数据制作json树?

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:20 24 4
gpt4 key购买 nike

请看一下我当前的 json。

[ 
{"mode": "AR","fname": "ta","lname":"da","w_lng":"2.xx","w_lat":"1.xx"....},
{"mode": "AR","fname": "ta","lname":"da","w_lng":"3.xx","w_lat": "4.xx"....},
{"mode": "AR","fname": "ka","lname":"ja","w_lng":"6.xx","w_lat": "5.xx"....}
]

现在我正在寻找:

{
"mode": "AR",
"results": [
{
"fname": "ta",
"lname": "da",
"w_level": [
{ "w_lng": "2.xx",
"w_lat": "1.xx"
"anothelevel":[........]
},
{"w_lng": "3.xx",
"w_lat": "4.xx"
"anothelevel":[........]
}
]
}
{
"fname": "ka",
"lname": "ja",
"w_level": [
{
"w_lng": "x.xx",
"w_lat": "x.xx"
.....................
}
]
}
]
}

这与我们在 SQL group by 中所做的相同。假设首先按世界分组,然后按国家分组,然后按城市分组,然后按村庄分组等。我通过分组进行了尝试。但结果不是我预期的输出。请建议我应该做什么。

最佳答案

objMap = {};
for (let temp of obj) {
if (!objMap[temp.mode]) {
objMap[temp.mode] = { mode: temp.mode, results: [] }
}
let tempObj = { w_level: [], fname: temp.fname, lname: temp.lname };
let w_level = {};
for (let key of Object.keys(temp)) {
if (key !== "fname" && key !== 'lname' && key !== 'mode') {

w_level[key] = temp[key];

}


}
tempObj.w_level.push(w_level)
objMap[temp.mode].results.push(tempObj)
}


NOTE:get object by using Object.values(objMap);

关于javascript - 如何通过group by json数据制作json树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59764965/

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