如何在 JavaScript 中将两个数组合并为一个对象数组?
假设我们的两个数组如下 −
var firstArray = ['John', 'David', 'Bob']; var secondArray = ['Mike','Sam','Carol'];
若要将两个数组合并为一个对象数组,请使用 JavaScript 中的 map() 函数。
示例
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);若要运行上述程序,你需要使用以下命令 −
node fileName.js.
此处,我的文件名为 demo190.js。
输出
这将产生以下输出 −
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' ] ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP