我有几个如下所示的数组:
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'}
];
最佳答案
纯 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);
关于javascript - 将javascript中的数组组合成一个哈希数组,其中一个数组是所有键,其余是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38445435/