मान लीजिए, हमारे पास कुछ लोगों के बारे में डेटा वाला एक ऑब्जेक्ट है जैसे −
const obj = { "Person1_Age": 22, "Person1_Height": 170, "Person1_Weight": 72, "Person2_Age": 27, "Person2_Height": 160, "Person2_Weight": 56 };हमें एक JavaScript फ़ंक्शन लिखना आवश्यक है जो ऐसा एक ऑब्जेक्ट लेता है। और हमारा फ़ंक्शन प्रत्येक अद्वितीय व्यक्ति के बारे में डेटा को उनके अपने ऑब्जेक्ट्स में अलग करना चाहिए।
इसलिए, उपरोक्त ऑब्जेक्ट के लिए आउटपुट इस तरह दिखना चाहिए −
const output = [ { "name": "Person1", "age": "22", "height": 170, "weight": 72 }, { "name": "Person2", "age": "27", "height": 160, "weight": 56 } ];उदाहरण
इसके लिए कोड होगा −
const obj = { "Person1_Age": 22, "Person1_Height": 170, "Person1_Weight": 72, "Person2_Age": 27, "Person2_Height": 160, "Person2_Weight": 56 }; const separateOut = (obj = {}) => { const res = []; Object.keys(obj).forEach(el => { const part = el.split('_'); const person = part[0]; const info = part[1].toLowerCase(); if(!this[person]){ this[person] = { "name": person }; res.push(this[person]); } this[person][info] = obj[el]; }, {}); return res; }; console.log(separateOut(obj));आउटपुट
और कंसोल में आउटपुट होगा −
[ { name: 'Person1', age: 22, height: 170, weight: 72 }, { name: 'Person2', age: 27, height: 160, weight: 56 } ]