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?
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])))));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);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.