मान लीजिए, हमारे पास निम्नलिखित 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" } ] } ] } ]