

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting two arrays into a JSON object 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}, ];
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
[ { opt: 'A', val: true }, { opt: 'B', val: false }, { opt: 'C', val: false }, { opt: 'D', val: false } ]
- Related Questions & Answers
- Converting array of arrays into an object in JavaScript
- JavaScript Converting array of objects into object of arrays
- Can we convert two arrays into one JavaScript object?
- How to deserialize a JSON into Javascript object?
- How to transform JSON text into a JavaScript object?
- How to turn a JSON object into a JavaScript array in JavaScript ?
- JavaScript JSON Arrays
- How to convert a JSON string into a JavaScript object?
- Converting a comma separated string to separate arrays within an object JavaScript
- Strip quotes with JavaScript to convert into JSON object?
- JavaScript group a JSON object by two properties and count
- Sorting a JSON object in JavaScript
- Flattening a JSON object in JavaScript
- How to add two arrays into a new array in JavaScript?
- How to combine 2 arrays into 1 object in JavaScript
Advertisements