简体   繁体   中英

Combining arrays in javascript into an array of hashes where one array is all the keys the rest are values

I have a couple of arrays that look like the following:

var foo = ['id', 'first', 'last'];
var student1 = ['1', 'sam', 'smith'];
var student2 = ['2', 'jon', 'murphy'];

Is there an efficient tool, perhaps using a library like underscore.js or vanilla javascript that will allow you to turn those three arrays into an object that looks like the following:

var finalObj = [ {'id' => 1, 'first' => 'sam', 'last' => 'smith'}, {'id' => 2, 'first' => 'jon', 'last' => 'murphy'} ];

A solution in plain 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 with 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); 

Assuming that the order of the arrays always matters (it will always be ID, First, Last) - you could do something like:

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]

Underscore can help, for example:

_.map( [student1, student2], function(arr) {
     return _.object(foo, arr);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM