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

133
Visualizações
How to add a unique ID to each entry in my JSON object?

I have this array of JSON objects:

JSON

and I want to add a unique ID (string) to each entry, like this:

let myTree = [
    {
        text: 'Batteries',
        id: '0',
        children: [
            {
                text: 'BatteryCharge',
                id: '0-0'
            },
            {
                text: 'LiIonBattery',
                id: '0-1'
            }
        ]
    },
    {
        text: 'Supplemental',
        id: '1',
        children: [
            {
                text: 'LidarSensor',
                id: '1-0',
                children: [
                    {
                        text: 'Side',
                        id: '1-0-0'
                    },
                    {
                        text: 'Tower',
                        id: '1-0-1'
                    }
                ]
            }
        ]
    }
]

I just can't think of the right logic to achieve this. I have written this recursive function, which obviously does not achieve what I want:

function addUniqueID(tree, id=0) {
    if(typeof(tree) == "object"){
        // if the object is not an array
        if(tree.length == undefined){
            tree['id'] = String(id);
        }
        for(let key in tree) {
            addUniqueID(tree[key], id++);
        }
    }
}
addUniqueID(myTree);

How can I solve this problem?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Instead of using a number/id in the recursive function I build a string.

let myTree = [{
    text: 'Batteries',
    children: [{
        text: 'BatteryCharge'
      },
      {
        text: 'LiIonBattery'
      }
    ]
  },
  {
    text: 'Supplemental',
    children: [{
      text: 'LidarSensor',
      children: [{
          text: 'Side'
        },
        {
          text: 'Tower'
        }
      ]
    }]
  }
];


function addUniqueID(arr, idstr = '') {
  arr.forEach((obj, i) => {
    obj.id = `${idstr}${i}`;
    if (obj.children) {
      addUniqueID(obj.children, `${obj.id}-`);
    }
  });
}

addUniqueID(myTree);

console.log(myTree);

over 4 years ago · Santiago Trujillo 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