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

151
Visualizações
¿Cómo convertir una matriz con un objeto anidado en un objeto?

Soy novato en JS, agradeceré cualquier ayuda.

Tengo una respuesta del servidor como esta:

 let arr = [ { key: "name", propertyValue: "Test Name", }, { key: "middleName", propertyValue: null, }, { key: "university.isGraduated", propertyValue: true, }, { key: "university.speciality", propertyValue: "Computer Science", }, { key: "university.country.code", propertyValue: "PL" }];

Y necesito convertirlo en objeto:

 let student = { name: 'Test Name', middleName: null, university: { isGraduated: true, speciality: 'Computer Science', country: { code: 'PL' } }

}

¿Alguien tiene alguna idea de cómo hacer esto?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Por favor comprueba esto:

 const array=[{key:"name",propertyValue:"Test Name"},{key:"middleName",propertyValue:null},{key:"university.isGraduated",propertyValue:!0},{key:"university.speciality",propertyValue:"Computer Science"},{key:"university.country.code",propertyValue:"PL"}]; const student = {}; array.forEach(e => { // loop trought let obj = student; e.key.split('.').forEach((a,b,c) => ( // go way trough (obj[a] = b === c.length - 1 ? e.propertyValue : obj[a] || {}), (obj = obj[a]) // update obj )) }); console.log(student)

O como una frase "bonita":

 array.forEach((e, o) => ((o = student), e.key.split('.').forEach((a,b,c) => ((o[a] = b === c.length - 1 ? e.propertyValue : o[a] || {}), (o = o[a])))));
about 4 years ago · Juan Pablo Isaza Relatório

0

Puede usar una combinación de reduce y split para construir el objeto.

 let arr = [ { key: "name", propertyValue: "Test Name", }, { key: "middleName", propertyValue: null, }, { key: "university.isGraduated", propertyValue: true, }, { key: "university.speciality", propertyValue: "Computer Science", }, { key: "university.country.code", propertyValue: "PL" }]; const result = arr.reduce ( (acc,i) => { const keys = i.key.split("."); let pointer = acc; for(let i=0;i<keys.length-1;i++) pointer = pointer[keys[i]] || (pointer[keys[i]] = {}); pointer[keys[keys.length-1]] = i.propertyValue; return acc; },{}); console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

sin objeto anidado esto sería tan simple como eso:

arr.reduce((prev, current) => {return prev[current.key] = current.propertyValue}, {})

Con su formato de datos, primero haría current.key.split('.') y luego construiría el objeto recursivamente usando la función de reduce de arriba.

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