Question

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/

Was it helpful?

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

OTHER TIPS

I'd use each() like this because map() returns element of an array as stated in the docs:

jQuery.map( array, callback(elementOfArray, indexInArray) )
Returns: Array
Description: Translate all items in an array or object to new array of items.

var classname = "username_admin color_red strength_good";

var res = {};
$.each(classname.split(' '),function(i, el) {
    var tmp = el.split('_');

    res[tmp[0]] = tmp[1];
});


console.log(res);

fiddle here http://jsfiddle.net/4EvWw/1/

You want to use .each rather than .map, and define res outside of the function:

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

console.log(res);

http://jsfiddle.net/infernalbadger/4EvWw/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top