flattening nested arrays/objects in underscore.js

前端 未结 1 1021
心在旅途
心在旅途 2021-01-05 18:35

I have an array of objects as shown below (although the example below has just one element in the array)

[
    {
        \"uptime\":0,
        \"load\":{\"x\         


        
相关标签:
1条回答
  • 2021-01-05 18:43

    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
    }    
    
    0 讨论(0)
提交回复
热议问题