无法将 JSON 的对象转换为 Angular 中的 key/value 对 7
Not able to convert the object of JSON to key/value pair in Angular 7
我需要像这样转换我的 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 转换为 key/value 对:
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;
});
有什么好的方法吗?
根据您修改后的问题,试试这个:
this.cacheMapDataDto.forEach(cacheMapDataDto => {
let result = Object.assign(cacheMapDataDto)
result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})
我需要像这样转换我的 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 转换为 key/value 对:
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;
});
有什么好的方法吗?
根据您修改后的问题,试试这个:
this.cacheMapDataDto.forEach(cacheMapDataDto => {
let result = Object.assign(cacheMapDataDto)
result.mapObj = Object.keys(cacheMapDataDto.mapObj).map(key => ({ key, value: cacheMapDataDto.mapObj[key] }));
})