0

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?

1
  • Hi Ashwin, hope this help : your "Cannot convert undefined or null to object" error depends on how you're accessing your object. Regarding your conversion just need to change it a bit to : this.result = Object.keys(cacheMapDataDto).map(function(key) { return { "id": key, "value": cacheMapDataDto[key]}; }); Hope this helps. Commented Sep 25, 2019 at 9:17

1 Answer 1

1

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

Working Stackbiltz

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.