Elsendion Elsendion - 14 days ago 8
Javascript Question

Rename json keys iterative

I got a very simple json but in each block I got something like this.

var json = {
"name": "blabla"
"Children": [{
"name": "something"
"Children": [{ ..... }]
}


And so on. I don't know how many children there are inside each children recursively.

var keys = Object.keys(json);

for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = json[key];
delete json[key];
key = key.replace("Children", "children");
json[key] = value;
}


And now I want to replace all "Children" keys with lowercase "children". The following code only works for the first depth. How can I do this recursively?

Answer

It looks the input structure is pretty well-defined, so you could simply create a recursive function like this:

function transform(node) {
  return {
    name: node.name,
    children: node.Children.map(transform)
  };
}


var json = {
  "name": "a",
  "Children": [{
    "name": "b",
    "Children": [{
      "name": "c",
      "Children": []
    }, {
      "name": "d",
      "Children": []
    }]
  }, {
    "name": "e",
    "Children": []
  }]
};

console.log(transform(json));