मान लीजिए, हमारे पास ऑब्जेक्ट्स का एक ऐरे है जैसे कि -
const arr = [{ name : 'Client 1', total: 900, value: 12000 }, { name : 'Client 2', total: 10, value: 800 }, { name : 'Client 3', total: 5, value : 0 }];हमें एक JavaScript फ़ंक्शन लिखना है जो ऐसा ऐरे लेता है और प्रत्येक ऑब्जेक्ट प्रॉपर्टी के लिए एक अलग ऐरे निकालता है।
इसलिए, प्रत्येक ऑब्जेक्ट की name प्रॉपर्टी के लिए एक ऐरे, एक total के लिए और एक value के लिए। यदि और प्रॉपर्टीज़ होतीं, तो हम उनके लिए भी अलग ऐरे निकालते।
उदाहरण
इसका कोड होगा -
const arr = [{ name : 'Client 1', total: 900, value: 12000 }, { name : 'Client 2', total: 10, value: 800 }, { name : 'Client 3', total: 5, value : 0 }]; const separateOut = arr => { if(!arr.length){ return []; }; const res = {}; const keys = Object.keys(arr[0]); keys.forEach(key => { arr.forEach(el => { if(res.hasOwnProperty(key)){ res[key].push(el[key]) }else{ res[key] = [el[key]]; }; }); }); return res; }; console.log(separateOut(arr));आउटपुट
कंसोल में आउटपुट होगा -
{ name: [ 'Client 1', 'Client 2', 'Client 3' ], total: [ 900, 10, 5 ], value: [ 12000, 800, 0 ] }