1

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

[
  {
    "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 文档,但我不太清楚如何将它们放在一起。

4

1 回答 1

2

我认为你只需要处理你的结果数组,这可以使用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;
  }, [])); 
}, []));
于 2017-12-21T15:26:51.557 回答