Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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}
];
Using forEach with Object Assignment
The first approach uses nested forEach loops to transform the nested array structure into objects:
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));
[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]
Using map and Object.fromEntries (Modern Approach)
A cleaner solution using map() and Object.fromEntries():
const arr = [
[
['dog', 'Harry'], ['age', 2]
],
[
['dog', 'Roger'], ['age', 5]
]
];
const transformToObjects = (nestedArray) => {
return nestedArray.map(subArray => Object.fromEntries(subArray));
};
console.log(transformToObjects(arr));
[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]
Using reduce for Each Sub-array
Another approach using reduce() to build objects from key-value pairs:
const arr = [
[
['dog', 'Harry'], ['age', 2]
],
[
['dog', 'Roger'], ['age', 5]
]
];
const arrayToObjectsReduce = (nestedArray) => {
return nestedArray.map(subArray =>
subArray.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {})
);
};
console.log(arrayToObjectsReduce(arr));
[ { dog: 'Harry', age: 2 }, { dog: 'Roger', age: 5 } ]
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| forEach + Object.assign | Moderate | Good | All browsers |
| map + Object.fromEntries | High | Best | ES2019+ |
| map + reduce | High | Good | All modern browsers |
Conclusion
The Object.fromEntries() approach is the most concise and readable for transforming nested arrays to objects. Use reduce() for older browser compatibility.
Advertisements
