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
Creating an array of objects based on another array of objects JavaScript
In JavaScript, you can create a new array of objects based on an existing array by transforming each object's structure. This is commonly done using the map() method to extract specific properties and create new object formats.
Suppose we have an array of objects containing user data like this:
const arr = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
console.log("Original array:", arr);
Original array: [
{ user: 'dan', liked: 'yes', age: '22' },
{ user: 'sarah', liked: 'no', age: '21' },
{ user: 'john', liked: 'yes', age: '23' }
]
We want to transform this into a new array where each object contains the user's name as a key and their "liked" status as the value:
[
{"dan":"yes"},
{"sarah":"no"},
{"john":"yes"}
]
Using map() Method
The map() method creates a new array by transforming each element of the original array:
const arr = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
const mapToPair = (arr = []) => {
const result = arr.map(obj => {
const res = {};
res[obj['user']] = obj['liked'];
return res;
});
return result;
};
console.log(mapToPair(arr));
[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ]
Simplified Version
You can make the function more concise using object literal syntax:
const arr = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
const mapToPairSimple = (arr) => {
return arr.map(obj => ({
[obj.user]: obj.liked
}));
};
console.log(mapToPairSimple(arr));
[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ]
Alternative Approaches
You can also use destructuring assignment for cleaner code:
const arr = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
const mapWithDestructuring = (arr) => {
return arr.map(({user, liked}) => ({[user]: liked}));
};
console.log(mapWithDestructuring(arr));
[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ]
Key Points
- The
map()method transforms each element and returns a new array - Use square bracket notation
[obj.user]for dynamic property names - Object destructuring can make the code more readable
- The original array remains unchanged
Conclusion
Creating arrays of objects from existing arrays is efficiently handled using the map() method. This approach allows you to transform data structures while maintaining immutability and clean, readable code.
