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

136
Vistas
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 Respuestas
Responde la pregunta

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