js 递归修改json无限级key值

var tree=[

{
"ID": 2337,
"DeviceId": "95274278-32a4-4cd0-a023-5b475111db9f",
"DeviceName": "图像控制处理器",
"DeviceBrand": null,
"DeviceTypeId": null,
"DeviceLevel": 1,
"FactorySerial": " ",
"CompanySerial": "CY17099ICP0023",
"FModelSize": null,
"Childers": [
{
"ID": 2339,
"DeviceId": "8438bb54-5e17-472f-883a-7d12ea9866f2",
"DeviceName": "智能烟雾报警器",
"DeviceBrand": null,
"DeviceTypeId": null,
"DeviceLevel": 2,
"FactorySerial": " ",
"CompanySerial": "CY17099SRP0034",
"FModelSize": null,
"Childers": []
},
{
"ID": 2340,
"DeviceId": "cfa71e5f-d864-44eb-8564-4cb6132c53ba",
"DeviceName": "安防联动处理器",
"DeviceBrand": null,
"DeviceTypeId": null,
"DeviceLevel": 2,
"FactorySerial": " ",
"CompanySerial": "CY17099DCO0045",
"FModelSize": null,
"Childers": []
}
]
},
{
"ID": 2491,
"DeviceId": "83af5577-ed8b-4bab-802e-6f8a2b435fca",
"DeviceName": "小型气象站",
"DeviceBrand": null,
"DeviceTypeId": null,
"DeviceLevel": 1,
"FactorySerial": " ",
"CompanySerial": " 2",
"FModelSize": null,
"Childers": []
}
];

创建js文件
const key = "children";
export function parseJson(arr) {
arr = arr.slice();
function toParse(arr) {
arr.forEach(function (item) {
if (item.Childers && Array.isArray(item.Childers)) {
item[key] = item.Childers;
toParse(item[key]);
}
delete item.Childers;
});
return arr;
}
return toParse(arr);
}
在需要的地方引入
import { parseJson } from "../../utils/parseJson.js";
调用
parseJson (tree)
原文地址:https://www.cnblogs.com/wgy0528/p/10937448.html