我的示例 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 内容将类似于提供的示例。
您可以使用
迭代和递归方法将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; }