Javascript 无法将JSON的对象转换为Angular 7中的键/值对
我需要像这样转换JSON数据:Javascript 无法将JSON的对象转换为Angular 7中的键/值对,javascript,angular,typescript,angular7,Javascript,Angular,Typescript,Angular7,我需要像这样转换JSON数据: cacheMapDataDto = [{ "cacheName": "cache_nchl_individual_type", "count": 2, "mapObj": { "NCHL_BI_BATCH_VERIFICATION": false, "NCHL_STL_BATCH_VERIFICATION": false }, "nameOfCache": "NCHL Verification St
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"
};
因此,我尝试使用以下方法将mapofdo转换为键/值对:
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
有什么好方法吗?根据您修改的问题,尝试以下方法:
this.cacheMapDataDto.forEach(cacheMapDataDto => {
let result = Object.assign(cacheMapDataDto)
result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})
你好,Ashwin,希望有帮助:不能将未定义或null转换为对象错误取决于您访问对象的方式。关于转换,只需将其稍微更改为:this.result=Object.keyscacheMapDataDto.mapfunctionkey{return{id:key,value:cacheMapDataDto[key]};};希望这有帮助。
this.cacheMapDataDto.forEach(cacheMapDataDto => {
let result = Object.assign(cacheMapDataDto)
result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})