Search code examples
javascriptjavascript-objects

Change the nested objects’ keys recursively


I have object like this which contains many keys named label and choices:

const obj = {
  "label": "mylabel",
  "choices": [
    {
      "label": "mylabel_11",
      "choices": {
        "label": "mylabel_12",
        "choices": [ /* … */ ]
      }
    },
    {
      "label": "mylabel_21",
      "choices": {
        "label": "mylabel_22",
        "choices": [ /* … */ ]
      }
    },
  ]
}

I want to change all "label" to "name", and all "choices" to "children".

Is there any recursive way to replace the name?

Currently my idea is this:

const new_keys = {};

for (const key in obj) {
  const old_key = key;

  key = key.replace("label", "name");
  key = key.replace("choices", "children");
  new_keys[key] = obj[old_key]
}

How can I make this recursive?


Solution

  • IMHO the easiest way would be to use string.replace. All code in one line

    var obj=JSON.parse(JSON.stringify(obj).replaceAll("\"label\":","\"name\":")
    .replaceAll("\"choices\":","\"children\":"));
    

    result

    {
      "name": "mylabel",
      "children": [
        {
          "name": "mylabel_11",
          "children": {
            "name": "mylabel_12",
            "children": []
          }
        },
        {
          "name": "mylabel_21",
          "children": {
            "name": "mylabel_22",
            "children": []
          }
        }
      ]
    }