我有几个如下所示的数组:
var foo = ['id', 'first', 'last'];
var student1 = ['1', 'sam', 'smith'];
var student2 = ['2', 'jon', 'murphy'];
是否有一个有效的工具,可能使用像underscore.js
或vanilla
javascript这样的库,它允许您将这三个数组转换为如下所示的对象:
var finalObj = [
{'id' => 1, 'first' => 'sam', 'last' => 'smith'},
{'id' => 2, 'first' => 'jon', 'last' => 'murphy'}
];
答案 0 :(得分:2)
普通Javascript中的解决方案
var foo = ['id', 'first', 'last'],
student1 = ['1', 'sam', 'smith'],
student2 = ['2', 'jon', 'murphy'],
result = [student1, student2].map(function (a) {
var o = {};
foo.forEach(function (k, i) {
o[k] = a[i];
});
return o;
});
console.log(result);

ES6与Array#reduce
var keys = ['id', 'first', 'last'],
st1 = ['1', 'sam', 'smith'],
st2 = ['2', 'jon', 'murphy'],
result = [st1, st2].map(a => keys.reduce((o, k, i) => (o[k] = a[i], o), {}));
console.log(result);

答案 1 :(得分:0)
假设数组的顺序总是重要的(它总是ID,First,Last) - 你可以这样做:
var people = [student1, student2]; //create 2d array
var finalObj = people.reduce(function(final, person) {
var obj = {};
obj[foo[0]] = person[0]
obj[foo[1]] = person[1]
obj[foo[2]] = person[2]
final.push(obj);
return final;
}, []);
//[Objectfirst: "sam"id: "1"last: "smith"__proto__: Object, Objectfirst: "jon"id: "2"last: "murphy"__proto__: Object]
答案 2 :(得分:0)
下划线可以提供帮助,例如:
_.map( [student1, student2], function(arr) {
return _.object(foo, arr);
})