How to combine two arrays into an array of objects in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following are our two arrays −

var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike','Sam','Carol'];

To combine two arrays into an array of objects, use map() from JavaScript.

Example

var firstArray = ['John', 'David', 'Bob'];
var secondArray = ['Mike','Sam','Carol'];
var arrayOfObject = firstArray.map(function (value, index){
   return [value, secondArray[index]]
});
console.log("The First Array=");
console.log(firstArray);
console.log("The Second Array=");
console.log(secondArray);
console.log("The mix Of array object=");
console.log(arrayOfObject);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo190.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo190.js
The First Array=
[ 'John', 'David', 'Bob' ]
The Second Array=
[ 'Mike', 'Sam', 'Carol' ]
The mix Of array object=
[ [ 'John', 'Mike' ], [ 'David', 'Sam' ], [ 'Bob', 'Carol' ] ]
raja
Published on 14-Sep-2020 08:26:33
Advertisements