Skip to content Skip to sidebar Skip to footer

Flattening Nested Arrays/objects In Underscore.js

I have an array of objects as shown below (although the example below has just one element in the array) [ { 'uptime':0, 'load':{'x':0.11,'y':0.22,'z':0.33},

Solution 1:

For example:

flatten = function(x, result, prefix) {
    if(_.isObject(x)) {
        _.each(x, function(v, k) {
            flatten(v, result, prefix ? prefix + '_' + k : k)
        })
    } else {
        result[prefix] = x
    }
    return result
}


a =
{
    "uptime":0,
    "load":{"x":0.11,"y":0.22,"z":0.33},
    "cpu":[
        {"u":111,"n":112,"s":113,"i":114,"q":115},
        {"u":211,"n":212,"s":213,"i":214,"q":215}
    ]
}


result = flatten(a, {})

{
        "uptime": 0,
        "load_x": 0.11,
        "load_y": 0.22,
        "load_z": 0.33,
        "cpu_0_u": 111,
        "cpu_0_n": 112,
        "cpu_0_s": 113,
        "cpu_0_i": 114,
        "cpu_0_q": 115,
        "cpu_1_u": 211,
        "cpu_1_n": 212,
        "cpu_1_s": 213,
        "cpu_1_i": 214,
        "cpu_1_q": 215
}    

Post a Comment for "Flattening Nested Arrays/objects In Underscore.js"