1

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'} ];

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

0

Underscore can help, for example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.