我的示例JSON,我想通过删除" Child:"来重建json以下。对象
{
"Child":{
"DeviceList":[
{
"Child":null,
"DeviceId":"7405618",
"Signal":"-90"
},
{
"Child":{
"DeviceList":[
{
"Child":{
"DeviceList":[
{
"Child":null,
"DeviceId":"3276847",
"Signal":"-86"
}
]
},
"DeviceId":"2293808",
"Signal":""
}
]
},
"DeviceId":"4915247",
"Signal":"-90"
}
]
}
}
新结构应如下所示
{
"DeviceList":[
{
"DeviceList":null,
"DeviceId":"7405618",
"Signal":"-90"
},
{
"DeviceList":[
{
"DeviceList":[
{
"DeviceList":null,
"DeviceId":"3276847",
"Signal":"-86"
}
],
"DeviceId":"2293808",
"Signal":""
}
],
"DeviceId":"4915247",
"Signal":"-90"
}
],
"DeviceId":"4915247",
"Signal":"-90"
}
我正在寻找一个动态json树结构的嵌套递归解决方案,其中我的JSON内容看起来就像提供的样本一样。
答案 0 :(得分:1)
您可以使用迭代和递归方法将DeviceList
移动到Child
的位置。
var data = { Child: { DeviceList: [{ Child: null, DeviceId: "7405618", Signal: "-90" }, { Child: { DeviceList: [{ Child: { DeviceList: [{ Child: null, DeviceId: "3276847", Signal: "-86" }] }, DeviceId: "2293808", Signal: "" }] }, DeviceId: "4915247", Signal: "-90" }] } };
[data].forEach(function iter(a) {
if ('Child' in a) {
a.DeviceList = a.Child && a.Child.DeviceList;
delete a.Child;
if (Array.isArray(a.DeviceList)) {
a.DeviceList.forEach(iter);
}
}
});
console.log(data);

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