Search code examples
javascriptnode.jsangularhighcharts-ng

Json object to arrays for network graph


I am trying to build a network graph which has the points data as [[from, to], [from,to]]. So, I need to build an array of this form from a JSON object. Can you give me a way that I can do it? I know, its just the way how we apply logic, but I tried lot many ways and I couldn't able to do it. Hence I am here to get a nice logic which applies for any depth of object.

My sample object is like

myObj = {
  Continents : 
  { Asia : {
      India : 1,
      China: 2 ,
      Japan : 3
    },
    Europe : {
      Sweden: 1,
      Norway : 2,
      Finland : 4,
      Denmark : 5
    },
    Africa : {
      Congo : 1,
      Kenya: 2,
      Zimbabwe : 3
    }
  }
}

Depth of the object can vary. And now I have to make an array to form nodes as below.

myArray = [['Continents', 'Asia'],
           ['Continents', 'Europe'],
           ['Continents'], 'Africa'],
           ['Asia','India'],
           ['Asia','China'],
           ['Asia','Japan'],
           ['Europe', 'Sweden'],
           ['Europe', 'Norway'],
           ['Europe', 'Finland'],
           ['Europe', 'Denmark'],
           ['Africa', 'Congo'],
           ['Africa', 'Kenya'],
           ['Africa', 'Zimbabwe'],
]

Solution

  • You could use a recursive generator:

      function* pairs(obj, parent) {
        for(const [key, value] of Object.entries(obj)) {
           if(parent) yield [parent, key];
           if(typeof value === "object")
              yield* pairs(value, key);
        }
     }
    

    Usable as:

      const result = [...pairs(obj)];