Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert array with nested object to object?

I am newbie in JS, I will appreciate any help

I have response from server like this:

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"
}];

And I need to convert it to object:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

}

Does anyone have any ideas how to do this?

>Solution :

You can use a combination of reduce and split to build up the object.

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading