Search code examples
javascriptnode.jscoffeescriptunderscore.js

merge two arrays (keys and values) into an object


Is there a common Javascript/Coffeescript-specific idiom I can use to accomplish this? Mainly out of curiosity.

I have two arrays, one consisting of the desired keys and the other one consisting of the desired values, and I want to merge this in to an object.

keys = ['one', 'two', 'three']
values = ['a', 'b', 'c']

Solution

  • var r = {},
        i,
        keys = ['one', 'two', 'three'],
        values = ['a', 'b', 'c'];
    
    for (let i = 0; i < keys.length; i++) {
        r[keys[i]] = values[i];
    }
    
    console.log(r);
    .as-console-wrapper { max-height: 100% !important; top: 0; }