मान लीजिए हमारे पास ऐरे का ऐरे है:
const arr = [ [ ['juice', 'apple'], ['maker', 'motts'], ['price', 12] ], [ ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11] ] ];
हमें एक जावास्क्रिप्ट फंक्शन लिखना है जो ऐसा ऐरे ले और इनपुट ऐरे के आधार पर बने ऑब्जेक्ट्स का नया ऐरे वापस करे।
उपरोक्त ऐरे के लिए आउटपुट ऐसा दिखना चाहिए:
const output = [ {juice: 'apple', maker: 'motts', price: 12}, {juice: 'orange', maker: 'sunkist', price: 11} ];उदाहरण
इसके लिए कोड:
const arr = [ [ ['juice', 'apple'], ['maker', 'motts'], ['price', 12] ], [ ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11] ] ]; const arrayToObject = arr => { let res = []; res = arr.map(list => { return list.reduce((acc, val) => { acc[val[0]] = val[1]; return acc; }, {}); }); return res; }; console.log(arrayToObject(arr));आउटपुट
कंसोल में आउटपुट:
[ { juice: 'apple', maker: 'motts', price: 12 }, { juice: 'orange', maker: 'sunkist', price: 11 } ][ { juice: 'apple', maker: 'motts', price: 12 }, { juice: 'orange', maker: 'sunkist', price: 11 } ]