使用遞迴將 JSON 轉換為另一種 JSON 格式 JavaScript
假設,我們有以下 JSON 物件 −
const obj = { "context": { "device": { "localeCountryCode": "AX", "datetime": "3047-09-29T07:09:52.498Z" }, "currentLocation": { "country": "KM", "lon": -78789486, } } };
我們需要編寫一個 JavaScript 遞迴函式,該函式最初採用一個這樣的陣列。該函式應將上述物件拆分為“標籤” -“子項”格式。
因此,上述物件輸出應如下所示 −
const output = { "label": "context", "children": [ { "label": "device", "children": [ { "label": "localeCountryCode" }, { "label": "datetime" } ] }, { "label": "currentLocation", "children": [ { "label": "country" }, { "label": "lon" } ] } ] }
程式碼將如下所示 −
示例
const obj = { "context": { "device": { "localeCountryCode": "AX", "datetime": "3047-09-29T07:09:52.498Z" }, "currentLocation": { "country": "KM", "lon": -78789486, } } }; const transformObject = (obj = {}) => { if (obj && typeof obj === 'object') { return Object.keys(obj).map((el) => { let children = transformObject(obj[el]); return children ? { label: el, children: children } : { label: el }; }); }; }; console.log(JSON.stringify(transformObject(obj), undefined, 4));
輸出
並且控制檯中的輸出將如下所示 −
[ { "label": "context", "children": [ { "label": "device", "children": [ { "label": "localeCountryCode" }, { "label": "datetime" } ] }, { "label": "currentLocation", "children": [ { "label": "country" }, { "label": "lon" } ] } ] } ]
廣告