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

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

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