Search code examples
javascriptjqueryarray-map

jquery map convert list of dashed properties into object


I would like to convert something like this (used in eg. in class):

var classname = "username_admin color_red strength_good"

into:

myvalues = {
    username: 'admin',
    color: 'red',
    strength: 'good'
}

Here's at present my closest reach:

myvalues = $.map(classname.split(' '),function(el, i) {
    var tmp = el.split('_');
    var res = {};
    res[tmp[0]] = tmp[1];
    return res;
});

How to continue? http://jsfiddle.net/4EvWw/


Solution

  • updated your code to the following http://jsfiddle.net/manuel/4EvWw/2/

    var classname = "username_admin color_red strength_good";
    
    var res = {};
    $.map(classname.split(' '),function(el, i) {
        var tmp = el.split('_');
        res[tmp[0]] = tmp[1];
    });
    
    console.log(res);