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

135
Views
convertir matriz especial a objeto

Estoy tratando de convertir la siguiente matriz en un objeto:

 var arr = [ 'car.name', 'car.age', 'car.event.id', 'zz.yy.dd.aa', 'aa.yy.zz.dd.kk' ];

Entonces se verá así:

 var targetObject = { car: { name: '', age: '', event: { id: '' } } , zz: { yy: { dd: { aa: '' } } }, aa: { yy: { zz: { dd: { kk: '', } } } } }

Este es mi código:

 targetObject = {} function arrayToObject(arr){ //iterate through array and split into items for (var i = 0; i < arr.length; ++i){ var item = arr[i].split("."); //iterate through item that has just been splitted for (var u = 0; u < item.length; ++u){ //if item is not in targetobject create new object if(!(item[0] in targetObject)){ targetObject[item[0]] = {} } else { //else go into the object and add the item/property to the existing object targetObject[item[0]][item[u]] = {} } } } console.log(targetObject); } arrayToObject(arr);

Sale solo en el segundo nivel y no puedo descifrar cómo hacerlo con los varios niveles. Sé que el código es de la vieja escuela, por lo que también me gustaría saber cómo se puede hacer esto más fácilmente.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede usar forEach para recorrer la matriz y luego split con reduce para construir un objeto anidado.

 var arr = [ 'car.name', 'car.age', 'car.event.id', 'zz.yy.dd.aa', 'aa.yy.zz.dd.kk' ]; const result = {} arr.forEach(str => { str.split('.').reduce((r, e, i, a) => { return r[e] = (r[e] || (a[i + 1] ? {} : '')) }, result) }) console.log(result)

O con su enfoque con bucles for , solo necesita mantener alguna referencia y actualizar el objeto anidado actual, para que pueda hacerlo así.

 var arr = [ 'car.name', 'car.age', 'car.event.id', 'zz.yy.dd.aa', 'aa.yy.zz.dd.kk' ]; const targetObject = {} let ref = targetObject; function arrayToObject(arr) { //iterate through array and split into items for (var i = 0; i < arr.length; ++i) { var item = arr[i].split("."); //iterate through item that has just been splitted for (var u = 0; u < item.length; ++u) { const last = u == item.length - 1 const str = item[u] if (!ref[str]) { ref[str] = (last ? '' : {}) } ref = ref[str] if (last) { ref = targetObject; } } } } arrayToObject(arr); console.log(targetObject)

about 4 years ago · Juan Pablo Isaza 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!