Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
¿Cómo agregar una identificación única a cada entrada en mi objeto JSON?

Tengo esta matriz de objetos JSON:

JSON

y quiero agregar una ID única (cadena) a cada entrada, así:

 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' } ] } ] } ]

Simplemente no puedo pensar en la lógica correcta para lograr esto. He escrito esta función recursiva, que obviamente no logra lo que quiero:

 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);

¿Como puedó resolver esté problema?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

En lugar de usar un número/id en la función recursiva, construyo una cadena.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!