मान लीजिए, हमारे पास की/वैल्यू जोड़ी ऑब्जेक्ट्स के साथ एक JSON सरणी है जैसे −
const arr = [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }];हमें एक JavaScript फ़ंक्शन लिखना आवश्यक है जो ऐसी एक सरणी लेता है।
फ़ंक्शन को एक नई सरणी तैयार करनी चाहिए जहां डेटा इस जटिल संरचना के बजाय केवल की-वैल्यू के विरुद्ध सूचीबद्ध हो।
इसलिए, उपरोक्त सरणी के लिए, आउटपुट इस तरह दिखना चाहिए −
const output = { "name": "john", "number": "1234", "price": { "quantity": "20", "price": "200" } };उदाहरण
इसके लिए कोड होगा −
const arr = [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }]; const simplify = (arr = []) => { const res = {}; const recursiveEmbed = function(el){ if ('item' in el) { el.item.forEach(recursiveEmbed, this); return; }; if (Array.isArray(el.value)) { this[el.key] = {}; el.value.forEach(recursiveEmbed, this[el.key]); return; }; this[el.key] = el.value; }; arr.forEach(recursiveEmbed, res); return res; }; console.log(simplify(arr));आउटपुट
और कंसोल में आउटपुट होगा −
{ name: 'john', number: '1234', price: { quantity: '20', price: '200' } }