猿问

数组合并方法

var arr1=['name', 'age', 'home']
var arr2=[['a', 'b', 'c', 'd', 'e'], [1,2,3,4,5], ['one', 'two', 'three', 'four', 'five']]
var arr3=[{'name':'a','age':1, 'home':'one'}, {'name':'b','age':2, 'home':'two'}, {'name':'c','age':3, 'home':'three'}, {'name':'d','age':4, 'home':'four'}, {'name':'e','age':5, 'home':'five'}];
已知数组1和2,求写一种方法得到数组3的形式

慕哥9229398
浏览 408回答 2
2回答

梵蒂冈之花

function trans (names, arr) {&nbsp; let result = []&nbsp; for (let i = 0, len = arr[0].length; i < len; i++) {&nbsp; &nbsp; let obj = {}&nbsp; &nbsp; names.forEach((name, index) => {&nbsp; &nbsp; &nbsp; obj[name] = arr[index][i]&nbsp; &nbsp; })&nbsp; &nbsp; result.push(obj)&nbsp; }&nbsp; return result}var arr1=['name', 'age', 'home']var arr2=[['a', 'b', 'c', 'd', 'e'], [1,2,3,4,5], ['one', 'two', 'three', 'four', 'five']]trans(arr1, arr2)

牛魔王的故事

var arr1=['name', 'age', 'home']var arr2=[['a', 'b', 'c', 'd', 'e'], [1,2,3,4,5], ['one', 'two', 'three', 'four', 'five']]arr2[0].map((item, index) => {return arr1.reduce((a, b, i) => (a[b] = arr2[i][index], a), {})})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答