将JSON转换为另一种递归的JSON格式
问题描述:
请帮助我创建一个递归函数,将JSON从给定格式转换为下面的JSON。我有点失落如何去做。 谢谢你的帮助! 下面是我有和需要转换的示例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"
}
]
}
]
}
答
你可以检查对象是truthy和获取对象的键。然后返回每个键的对象与标签和一个儿童属性与函数的递归调用的结果。
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; }
+0
非常感谢! – Eden1971
什么给定的格式?如果没有你想要的格式和格式,我们不能回答这个问题。 – zack6849
您似乎忘记了包含相关信息。请包括您正在使用的数据的示例。 – Lix
谢谢你们,我添加了相关信息。 – Eden1971