根据 Angular 中的接口从 Map 创建 json 列表 9
Create json list from Map based on interface in Angular 9
我使用 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;
}
我的APIreturn一张图
{
"countryInstallHistory": {
"DZ": 1,
"SN": 3
}
}
在我的 angular 项目中,我可以遍历我的国家/地区列表。
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}
};
提前致谢
像上面一样添加数据转换功能?
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));
我会简单地使用 reduce
数组的功能来实现这一点。看下面的演示
let response = {
countryInstallHistory: {
DZ: 1,
SN: 3,
},
};
const mapData = Object.entries(response.countryInstallHistory).reduce(
(prev, [key, value]) => ({...prev, [key]: { value }}), {}
)
console.log(mapData );
我使用 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;
}
我的APIreturn一张图
{
"countryInstallHistory": {
"DZ": 1,
"SN": 3
}
}
在我的 angular 项目中,我可以遍历我的国家/地区列表。
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}
};
提前致谢
像上面一样添加数据转换功能?
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));
我会简单地使用 reduce
数组的功能来实现这一点。看下面的演示
let response = {
countryInstallHistory: {
DZ: 1,
SN: 3,
},
};
const mapData = Object.entries(response.countryInstallHistory).reduce(
(prev, [key, value]) => ({...prev, [key]: { value }}), {}
)
console.log(mapData );