Search code examples
javascriptarraysjsond3.jskey-value-coding

How to convert object JSON to a d3.js array data


I have the following dataset in JSON format which I want to convert to something I can work with in d3.js:

    {  
       "rank_type_1":{  
          "d1":0,
          "d2":1,
          "d3":2
       },
       "rank_type_2":{  
          "d1":1,
          "d2":0,
          "d3":2
       },
       "rank_type_3":{  
          "d1":2,
          "d2":0,
          "d3":1
       }
    }

I have 3 rank types according to which d1, d2 and d3 are ranked. Now, I want to convert it to the following format:

[
    {
     "id":d1
     "rank_type_1" :0
     "rank_type_2" :1
     "rank_type_3" :2
    },
    {
     "id":d2
     "rank_type_1" :1
     "rank_type_2" :0
     "rank_type_3" :2
    },
    {
     "id":d3
     "rank_type_1" :2
     "rank_type_2" :2
     "rank_type_3" :1
    }
]

The reason being that when I log the output of d3.csv function, it has a similar format. That is, it is an array of objects and the keys from the first object are converted into the values in the output array.

I have tried playing around with Object.entries, Object.keys, Object.values but with no success.


Solution

  • You can do this with Object.keys() and forEach() to loop object and add to array.

    var data = {"rank_type_1":{"d1":0,"d2":1,"d3":2},"rank_type_2":{"d1":1,"d2":0,"d3":2},"rank_type_3":{"d1":2,"d2":0,"d3":1}}
    
    var result = [];
    Object.keys(data).forEach(function(e) {
      var that = this;
      Object.keys(data[e]).forEach(function(a) {
        if(!that[a]) {
          that[a] = {id: a, [e]: data[e][a]}
          result.push(that[a])
        } else {
          Object.assign(that[a], {[e]: data[e][a]})
        }
      })
    }, {})
    
    console.log(JSON.stringify(result, 0, 4))