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 } ]