繁体   English   中英

如何在rxJS中展平或合并数组

[英]How to flatten or merge arrays in rxJS

我有一个结构,想将其展平为一个同类数组。 源数组如下所示:

[
  {
    "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}));

似乎应该有一种方法可以将属于每个国家的州合并为可观察的数组。 我已经阅读了concatMap,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;
  }, [])); 
}, []));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM