0

Hello I have json file:

var jsonData = {
  "name": "James",
  "age": 22,
  "nodes": [
    {
      "name": "John",
      "age": 24,
      "nodes": [
        {
          "name": "Jack",
          "age": 65,
          "nodes": [
            {
              "name": "Harry",
              "age": 70,
              "nodes": []
            }
          ]
        },
        {
          "name": "Joe",
          "age": 10,
          "nodes": []
        }
      ]
    },
    {
      "name": "Daniel",
      "age": 30,
      "nodes": []
    }
  ]
}

I need a function that returns output like this:

James 22
James - John 24
James - John - Jack 65
James - John - Jack - Harry 70
James - John - Joe 10
James - Daniel 30

I tried to use recursive function but I don't know how to return output like this one and return age only on last child..

Code:

var json = jsonData;
var prev = [];

function sortData(obj, prev) {
  var i = 0;
  prev.push(obj.name + " " + obj.age);
  console.log(prev);
  if (obj.nodes.length > 0) {
    while (i < obj.nodes.length) {
      sortData(obj.nodes[i], prev);
      i++;
      prev.pop();
    }
  }
}

sortData(json, prev);

My function returns output in multiple arrays, so I don't know how to operate with that to return output like that. Will be grateful for any help. Thanks!

Sandy Gifford
  • 7,219
  • 3
  • 35
  • 65
Medf101
  • 107
  • 1
  • 5
  • Check out *[Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/a/11922384/218196) - What if the "depth" of the data structure is unknown to me?* , the second example. – Felix Kling Oct 29 '18 at 22:55

1 Answers1

0

You might consider just passing around strings representing the current property path recursively, that way you can just concatenate and pass the value around without worrying about it being mutated. Also, it'll be a lot easier to use array methods like forEach than to use an i variable and manually iterate:

var jsonData={"name":"James","age":22,"nodes":[{"name":"John","age":24,"nodes":[{"name":"Jack","age":65,"nodes":[{"name":"Harry","age":70,"nodes":[]}]},{"name":"Joe","age":10,"nodes":[]}]},{"name":"Daniel","age":30,"nodes":[]}]}

function getAge({ name, age, nodes }, oldPropStr = '') {
  const propStr = (oldPropStr ? oldPropStr + ' - ' : '') + name;
  console.log(propStr + ' ' + age);
  nodes.forEach(node => getAge(node, propStr));
}
getAge(jsonData);

Also, you might note that the current variable name of jsonData is misleading. There's no such thing as a "JSON Object". If you have an object or array, then you have an object or array, full stop. JSON format is a method of representing an object in a string, like const myJSON = '{"foo":"bar"}'. If there are no strings, serialization, or deserialization involved, then JSON is not involved either. Maybe call the variable people or something instead?

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320