views:

226

answers:

3

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?

+1  A: 
function combineObject( keys, values)
{
    var obj = {};
    if ( keys.length != values.length)
       return null;
    for (var index in keys)
        obj[keys[index]] = values[index];
     return obj;
};


var your_obj = combine( your_keys, your_values);
Artem Barger
heh, i saw you fixed it so removed the comment, which you then responded to -- hurrah for async conversation :DYou should also avoid new Object as Object may be changed, but {} is spec'd as using the original Object constructor.
olliej
The function is still incorrect. combineObject(["height", "width"], ["12px", "24px"]).height incorrectly returns "24px".
Simon Lieschke
Thanks I've fixed it according to your comment, but I'm not sure that can be an issue, since once somebody changes the Object it's on purpose so maybe it better to be implied on all objects you will have.
Artem Barger
@Simon, you right, my fault, fixed.
Artem Barger
+2  A: 

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 :D

olliej
The long way it is, then :(
itsadok
A: 

In the jQuery-Utils project, the ArrayUtils module has a zip function implemented.

//...
zip: function(object, object2, iterator) {
    var output = [];
    var iterator = iterator || dummy;
        $.each(object, function(idx, i){
        if (object2[idx]) { output.push([i, object2[idx]]); }
    });
    return output;
}
//...
CMS
Hmm, but then what do you do with the array of tuples?
itsadok