Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
Change the nested objects key recursively

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?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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": []
      }
    }
  ]
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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),
            };
        }
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda