
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Transform Data from a Nested Array to an Object in JavaScript
Suppose, we have the following array of arrays −
const arr = [ [ ['dog', 'Harry'], ['age', 2] ], [ ['dog', 'Roger'], ['age', 5] ] ];
We are required to write a JavaScript function that takes in one such nested array. The function should then prepare an object based on the array.
The object for the above array should look like −
const output = [ {dog: 'Harry', age: 2}, {dog: 'Roger', age: 5} ];
Example
The code for this will be −
const arr = [ [ ['dog', 'Harry'], ['age', 2] ], [ ['dog', 'Roger'], ['age', 5] ] ]; const prepareObjectArray = (arr = []) => { const copy = arr.slice(); copy.forEach((el, ind, array) => { el.forEach((element, index, subArray) => { subArray[element[0]] = element[1]; }); el.length = 0; array[ind] = Object.assign({}, array[ind]); }); return copy; }; console.log(prepareObjectArray(arr));
Output
And the output in the console will be −
[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]
Advertisements