- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' } ]
- Related Articles
- Filter an array containing objects based on another array containing objects in JavaScript
- Filter JavaScript array of objects with another array
- Sort array based on presence of fields in objects JavaScript
- How to sort an array of objects based on the length of a nested array in JavaScript
- Modify an array based on another array JavaScript
- Using methods of array on array of JavaScript objects?
- Order an array of words based on another array of words JavaScript
- Sorting an array of objects by an array JavaScript
- Search from an array of objects via array of string to get array of objects in JavaScript
- Converting array of objects to an object of objects in JavaScript
- Sorting Array based on another array JavaScript
- Sort object array based on another array of keys - JavaScript
- Manipulating objects in array of objects in JavaScript
- Most efficient method to groupby on an array of objects - JavaScript
- JavaScript - length of array objects

Advertisements