How can we make an Array of Objects from n properties of n arrays in JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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


raja
Published on 01-Oct-2020 10:07:00
Advertisements