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

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



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' ] ]
Updated on: 2020-09-14T08:27:05+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements