请帮我创建一个递归函数,将JSON从给定格式转换为下面的JSON。我有点迷失了怎么办。 谢谢你的帮助! 下面是我已经需要转换的示例JSON格式。
提供:
{
"context": {
"device": {
"localeCountryCode": "AX",
"datetime": "3047-09-29T07:09:52.498Z"
},
"currentLocation": {
"country": "KM",
"lon": -78789486,
}
}
}
这就是我想要的:
{
"label": "context",
"children": [
{
"label": "device",
"children": [
{
"label": "localeCountryCode"
},
{
"label": "datetime"
}
]
},
{
"label": "currentLocation",
"children": [
{
"label": "country"
},
{
"label": "lon"
}
]
}
]
}
答案 0 :(得分:0)
您可以检查对象是否真实并获取对象的键。然后为每个键返回一个带有标签的对象和一个带有该函数递归调用结果的children属性。
function transform(o) {
if (o && typeof o === 'object') {
return Object.keys(o).map(function (k) {
var children = transform(o[k]);
return children ? { label: k, children: children } : { label: k };
});
}
}
var object = { context: { device: { localeCountryCode: "AX", datetime: "3047-09-29T07:09:52.498Z" }, currentLocation: { country: "KM", lon: -78789486, } } },
result = transform(object);
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }