【问题标题】:Not able to convert the object of JSON to key/value pair in Angular 7 [duplicate]无法将 JSON 的对象转换为 Angular 7 中的键/值对 [重复]
【发布时间】:2020-01-25 09:46:58
【问题描述】:

我需要像这样转换我的 JSON 数据:

 cacheMapDataDto = [{
    "cacheName": "cache_nchl_individual_type",
    "count": 2,
    "mapObj": {
      "NCHL_BI_BATCH_VERIFICATION": false,
      "NCHL_STL_BATCH_VERIFICATION": false
    },
    "nameOfCache": "NCHL Verification Status"
 }] 

到这里:

{"cacheName":"cache_member_dto_type",
"count":1,
"mapOfDto":[{"id":merCode,"value":"1"},{"id":merName,"value":"DE"},{"id":merId,"value":"10"}]
"nameOfCache":"Member DTO"
};

所以,我尝试使用以下方法将 ma​​pOfDto 转换为键/值对:

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


  }

但是,我得到的错误是:

TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at CacheMetaDataComponent.formatData

当我看到错误来自 ts 文件时,我在这行代码中遇到错误:

 this.result = Object.keys(cacheMapDataDto.mapOfDto).map(function(key) {
    return this.result[key] =cacheMapDataDto.mapOfDto[key], this.result;
  });

有什么好的方法吗?

【问题讨论】:

  • 您好 Ashwin,希望对您有所帮助:您的“无法将未定义或 null 转换为对象”错误取决于您访问对象的方式。关于您的转换只需将其更改为:this.result = Object.keys(cacheMapDataDto).map(function(key) { return { "id": key, "value": cacheMapDataDto[key]}; }); 希望这会有所帮助。

标签: javascript angular typescript angular7


【解决方案1】:

根据您修改后的问题,试试这个:

this.cacheMapDataDto.forEach(cacheMapDataDto => {
      let result = Object.assign(cacheMapDataDto)
      result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})

Working Stackbiltz

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 2020-11-02
    • 2019-05-24
    • 2020-08-29
    • 2020-11-26
    • 1970-01-01
    • 2013-07-26
    • 2015-01-02
    • 2014-08-16
    相关资源
    最近更新 更多