Home > front end >  Change the nested objects key recursively
Change the nested objects key recursively

Time:02-17

I have object like this there are many keys named label choices

obj = 
{
 "label":"mylabel",
 "choices:[
    {
      "label":"mylabel_11",
      "choices":{
         "label":"mylabel_12",
         "choices":[...]
       }
    },{
      "label":"mylabel_21",
      "choices":{
         "label":"mylabel_22",
         "choices":[...]
       }
    },
  ]
}

Now I want to to change all "label" to "name", "choices" to "children"

Is there any recursive way to replace the name?

Currently my idea is

var new_keys;
for (key in obj){
    var 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?

CodePudding user response:

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": []
      }
    }
  ]
}

CodePudding user response:

You could look to use recursion in the following way, noting that the if statement accounts for the fact that your object's "choices" can be either an array or an object.

function replaceObject(yourObj) {
    if (yourObj.hasOwnProperty("label")) {
        if (Array.isArray(yourObj.choices)) {
            return {
                name: yourObj.label,
                children: yourObj.choices.map((choice) => {
                    return replaceObject(choice);
                }),
            };
        } else {
            return {
                name: yourObj.label,
                children: replaceObject(yourObj.choices),
            };
        }
    }
}

CodePudding user response:

I think you're asking for a way to make it go arbitrarily deep into your object. I think this could work:

function recursiveKeyRename(obj) {
  var new_keys;
  for (key in obj){
    var old_key = key;
    key = key.replace("label","name");
    key = key.replace("choices","children");
    new_keys[key] = obj[old_key]
  };
  if (obj.children && obj.children.choices)
  {
    recursiveKeyRename(obj.children.choices)
  };
};

I haven't really tested that, and that only works if all of you "choices" are objects, not arrays like you (maybe?) implied in your example. It can easily be retooled for whichever use case, though.

  • Related