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