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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM