基于Angular 9中的接口从Map创建json列表



我使用countries-map插件来获得具有数据值的映射。这个插件提供了这个数据示例

mapData: CountriesData = {
'ES': { 'value': 416 },
'GB': { 'value': 94},
'FR': { 'value': 255 }
};

基于这些接口

interface CountriesData {
[countryCode: string]: CountryData;
}
interface CountryData {
value: number;
extra?: CountryExtraData;
}
interface CountryExtraData {
[key: string]: number |string;
}

我的API返回地图

{
"countryInstallHistory": {
"DZ": 1,
"SN": 3
}
}

在我的棱角分明的项目中,我可以循环浏览我的国家列表。

for (let [key, result] of Object.entries(this.apkHistorDto.countryInstallHistory)) {
console.log(key)
console.log(result)
}

我如何使用API发送的数据创建这样一个基于接口的列表?

mapData: CountriesData = {
'DZ': { 'value': 1},
'SN': { 'value': 3}
};

提前感谢

我会简单地使用数组的reduce函数来实现这一点。参见下面的演示

let response = {
countryInstallHistory: {
DZ: 1,
SN: 3,
},
};

const mapData = Object.entries(response.countryInstallHistory).reduce(
(prev, [key, value]) => ({...prev, [key]: { value }}), {}
)
console.log(mapData );

是否添加如上所述的数据转换函数?

function convertData(data) {
let _result = {};
let result = data.countryInstallHistory;
for (let key in result) {
_result[key] = { value: result[key] };
}
return _result;
}
let result = {
countryInstallHistory: {
DZ: 1,
SN: 3,
},
};
console.log(convertData(result));

最新更新