Home > OS >  How to convert array with nested object to object?
How to convert array with nested object to object?

Time:01-29

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:

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?

CodePudding user response:

Please check this out:

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)

Or as "pretty" one-liner:

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

CodePudding user response:

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

CodePudding user response:

without nested object this would be simple as that:

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

With your data format I would first do current.key.split('.') and then build the object recursively using the reduce function from above.

  •  Tags:  
  • Related