I am dealing with an object structure like the one below:
let a = {
title: {
value:"developer"
}
publishedOn:{
month:{
value:"jan"
}
year:{
value:"2000"
}
}
and I need to transform it into the following object format:
let b = {
title : "Developer"
publishedOn:{
month:"jan",
year:"2000"
}
}
The challenge is that we do not have prior knowledge of the properties inside the a
variable. I attempted an iterative method, but I believe there might be a better solution out there. Any help or suggestions for improvement would be greatly appreciated.
function set(path, value) {
var schema = obj;
var pList = path.split('.');
var len = pList.length;
for(var i = 0; i < len-1; i++) {
var elem = pList[i];
if( !payload[elem] ) payload[elem] = {}
payload = payload[elem];
}
payload[pList[len-1]] = value;
console.log(payload);
}
Object.keys(this.formObject).forEach((key)=> {
if (Object.prototype.hasOwnProperty.call(this.formObject, key)) {
this.getPath(this.formObject[key],key).then((data:any)=>{
set(data.path, data.value);
});
}
});
}
async getPath(obj,path) { //publishedOn , month, yeaer
let value = "";
Object.keys(obj).forEach((key)=> {//month
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if(key === "value"){
path = path;
value = obj[key]
}else{
path = path + "." + key; // publishedOn.month
value = obj[key]['value']; // june
}
}
});
return {path,value }
}