使用递归 JavaScript 将 JSON 转换为另一种 JSON 格式
javascriptweb developmentfront end technologyobject oriented programmingjson
假设,我们有以下 JSON 对象 −
const obj = { "context": { "device": { "localeCountryCode": "AX", "datetime": "3047-09-29T07:09:52.498Z" }, &"currentLocation";: { &"country";: &"KM";, &"lon";: -78789486, } } };
我们需要编写一个 JavaScript 递归函数,该函数最初接受一个这样的数组。该函数应将上述对象拆分为"label"-"children"格式。
因此,上述对象的输出应如下所示 −
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" } ] } ] } ]