Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda