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