I need to convert my JSON data from like this :
cacheMapDataDto = [{
"cacheName": "cache_nchl_individual_type",
"count": 2,
"mapObj": {
"NCHL_BI_BATCH_VERIFICATION": false,
"NCHL_STL_BATCH_VERIFICATION": false
},
"nameOfCache": "NCHL Verification Status"
}]
To this:
{"cacheName":"cache_member_dto_type",
"count":1,
"mapOfDto":[{"id":merCode,"value":"1"},{"id":merName,"value":"DE"},{"id":merId,"value":"10"}]
"nameOfCache":"Member DTO"
};
So ,I tried to convert the mapOfDto to key/value pair using following approach:
formatData(cacheMapDataDto:any){
console.log("abc");
console.log(cacheMapDataDto);
this.result = Object.keys(cacheMapDataDto.mapOfDto).map(function(key) {
return this.result[key] =cacheMapDataDto.mapOfDto[key], this.result;
});
console.log(this.result);
this.cacheNewData={
"cacheName":cacheMapDataDto.cacheName,
"count":cacheMapDataDto.count,
"mapOfDto":this.result,
"nameOfCache": cacheMapDataDto.nameOfCache
};
console.log(this.cacheNewData);
}
But,I got the error as:
TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at CacheMetaDataComponent.formatData
I am getting error at this line of code when I see where is the error coming from ts file:
this.result = Object.keys(cacheMapDataDto.mapOfDto).map(function(key) {
return this.result[key] =cacheMapDataDto.mapOfDto[key], this.result;
});
Is there any good approach?
Based on your modified question, try this:
this.cacheMapDataDto.forEach(cacheMapDataDto => {
let result = Object.assign(cacheMapDataDto)
result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})