我有一个我想将其弄平为一个均匀数组的结构。源数组看起来像这样:
[
{
"countryCode": "CA",
"countryName": "Canada",
"states": [
{
"stateCode": "CAAB",
"stateName": "Alberta",
"countryCode": "CA",
"stateAbbrev": "AB"
},
. . .
{
"stateCode": "CAYT",
"stateName": "Yukon Territory",
"countryCode": "CA",
"stateAbbrev": "YT"
}
]
},
{
"countryCode": "US",
"countryName": "USA",
"states": [
{
"stateCode": "USAK",
"stateName": "Alaska",
"countryCode": "US",
"stateAbbrev": "AK"
},
. . .
{
"stateCode": "USWY",
"stateName": "Wyoming",
"countryCode": "US",
"stateAbbrev": "WY"
}
]
}
]
我想将其转变为这样的外观:
[
{
"value": "CA",
"label": "Canada"
},
{
"value": "CACB",
"label": "Alberta"
},
. . .
{
"value": "CAYT",
"label": "Yukon Territory"
},
{
"value": "US",
"label": "USA"
},
{
"value": "USAK",
"label": "Alaska"
},
. . .
{
"value": "USWY",
"label": "Wyoming"
}
]
到目前为止,我有:
let countries:Observable<ICountry[]> =
this.http.get<ICountry[]>(`${this.buildProUrl}/states`);
return countries.map(o => o.map(c =>
<IStateDropDownItem>{value: c.countryCode, label: c.countryName}));
似乎应该有一种方法可以将属于每个国家的州合并为可观察到的阵列。我已经阅读了condapmap,mergemap和switchmap文档,但我无法完全弄清楚如何将它们放在一起。
我认为您只需要处理结果数组,可以使用Arry.reduce()
函数完成:
const data = [
{
"countryCode": "CA",
"countryName": "Canada",
"states": [
{
"stateCode": "CAAB",
"stateName": "Alberta",
"countryCode": "CA",
"stateAbbrev": "AB"
},
{
"stateCode": "CAYT",
"stateName": "Yukon Territory",
"countryCode": "CA",
"stateAbbrev": "YT"
}
]
},
{
"countryCode": "US",
"countryName": "USA",
"states": [
{
"stateCode": "USAK",
"stateName": "Alaska",
"countryCode": "US",
"stateAbbrev": "AK"
},
{
"stateCode": "USWY",
"stateName": "Wyoming",
"countryCode": "US",
"stateAbbrev": "WY"
}
]
}
];
console.log(data.reduce((res, curr) => {
res.push({value: curr.countryCode, label: curr.countryName});
return res.concat(curr.states.reduce((res, curr) => {
res.push({value: curr.stateCode, label: curr.stateName});
return res;
}, []));
}, []));
如果您使用的是新的httpclient,那么您的响应已经是一个数组,因此在您的情况下应该有效:
let countries:Observable<ICountry[]> =
this.http.get<ICountry[]>(`${this.buildProUrl}/states`);
return countries.map(o => o.reduce((res, curr) => {
res.push(<IStateDropDownItem>{value: curr.countryCode, label: curr.countryName});
return res.concat(curr.states.reduce((res, curr) => {
res.push(<IStateDropDownItem>{value: curr.stateCode, label: curr.stateName});
return res;
}, []));
}, []));