Skip to content
Advertisement

Merge keys array and values array into an object in JavaScript

I have:

var keys = [ "height", "width" ];
var values = [ "12px", "24px" ];

And I’d like to convert it into this object:

{ height: "12px", width: "24px" }

In Python, there’s the simple idiom dict(zip(keys,values)). Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?

Advertisement

Answer

Simple JS function would be:

function toObject(names, values) {
    var result = {};
    for (var i = 0; i < names.length; i++)
         result[names[i]] = values[i];
    return result;
}

Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy 😀

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement