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
Selected Reading
Creating an array of objects based on another array of objects JavaScript
Suppose, we have an array of objects containing data about likes of some users like this −
const arr = [
{"user":"dan","liked":"yes","age":"22"},
{"user":"sarah","liked":"no","age":"21"},
{"user":"john","liked":"yes","age":"23"},
];
We are required to write a JavaScript function that takes in one such array. The function should construct another array based on this array like this −
const output = [
{"dan":"yes"},
{"sarah":"no"},
{"john":"yes"},
];
Example
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));
Output
And the output in the console will be −
[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ] Advertisements
