- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
How can we make an Array of Objects from n properties of n arrays in JavaScript?
Suppose we have two arrays of literals like these −
const options = ['A', 'B', 'C', 'D']; const values = [true, false, false, false];
We are required to write a JavaScript function that creates and returns a new Array of Objects from these two arrays, like this −
const response = [ {opt: 'A', val: true}, {opt: 'B', val: false}, {opt: 'C', val: false}, {opt: 'D', val: false}, ];
Example
Following is the code −
const options = ['A', 'B', 'C', 'D']; const values = [true, false, false, false]; const mapArrays = (options, values) => { const res = []; for(let i = 0; i < options.length; i++){ res.push({ opt: options[i], val: values[i] }); }; return res; }; console.log(mapArrays(options, values));
Output
This will produce the following output on console −
[ { opt: 'A', val: true }, { opt: 'B', val: false }, { opt: 'C', val: false }, { opt: 'D', val: false } ]
Advertisements