【发布时间】: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"
};
所以,我尝试使用以下方法将 mapOfDto 转换为键/值对:
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