1

I have the following issue. I have a flat json available from a URL which I want to load with Javascript as nested JSON in a d3.js chart. My code is as follows:

d3.json('http://88.99.13.199:3000/measures', function(err, mydata) { 
   mydata.forEach(function(val) { 
      var measuresdata=[];
      var ent = [];
      var plir = [];
      var subm = [];
      ent.push({
          name: "entaxeis",
          size: val.entaxeis
      });
      plir.push({
          name: "pliromes",
          size: val.pliromes
      });
      subm.push({
          name: val.submeasure_code,
          children:{ent, plir}
      });
      measuresdata.push({
          name: val.measure_code,
          children:{subm}
      });
      console.log(measuresdata);
   });
   console.log(measuresdata);
}); 

I want my json to be as follows:

{
   "name": "Μ01",
   "children": [
    {
     "name": "1.1",
     "children": [
      {"name": "entaxeis", "size": 456123},
      {"name": "pliromes", "size": 3812}
     ]
    }
   ]
  },
  {
   "name": "M03",
   "children": [
    {
     "name": "3.1",
     "children": [
      {"name": "entaxeis", "size": 456123},
      {"name": "pliromes", "size": 3812}
     ]
    },
   ]
 }
(..)

and so on. It's kind of a puzzle so any help would be great!

0

1 Answer 1

2

As you have added the d3.js tag, I think the easiest solution is to use the d3.nest() function to group by key, and then use the map function on the resulting array to create the required structure:

var nested = d3.nest()
  .key(function(d) { return d.measure_code; })
  .entries(mydata)
  .map(function(measure) {
    return {
      name: measure.key,
      children: measure.values.map(function(submeasure) {
        return {
          name: submeasure.submeasure_code,
          children: [
            { name: "entaxeis", size: submeasure.entaxeis },
            { name: "pliromes", size: submeasure.pliromes }
          ]
        };
      })
    };
  });
Sign up to request clarification or add additional context in comments.

2 Comments

I love your answer, however I have one issue. Your suggestion creates succesfully my JSON in the desired format, but it creates a record for eac measure_code although some are with the same name. I want it to put all submeasures under the same measure.
I've updated the answer to group the measures by measure_code by using d3.nest.

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.