2

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

great, thank you. Although, frankly speaking, I was expecting to get a "one-liner" :) Didn't expect it to be that complicated.
1

Possible solution using Array#reduce.

var obj = {"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}}, 
    res = Object.keys(obj).reduce(function(s,a,i) {
        var r = Object.keys(obj[a]).map((v, x) => ({["rank_type_"+[x+1]] : obj[a][v]})); 
        s.push(Object.assign({}, {id : "d"+(i+1)}, ...r));
        return s;
    }, []);

    console.log(res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.