【问题标题】:Append States to Countries from API Data将状态附加到 API 数据中的国家/地区
【发布时间】:2021-03-16 20:15:41
【问题描述】:

我有一个 API 以以下格式返回数据:

[
 {
  "id": 12,
  "acf": {
    "address": {
      "city": "Bandar Penawar",
      "state": "Johor",
      "country": "Malaysia",
   }
 },
 {
  "id": 16,
  "acf": {
    "address": {
      "city": "Some City",
      "state": "Arizona",
      "country": "United States",
   }
 }
]

现在,我正在使用以下计算代码获取国家和州的列表:

computed: {
    countries() {
      const countries = new Set();
      this.$store.state.posts.forEach((post) =>
        countries.add(post.acf.address.country)
      );
      return Array.from(countries);
    },
    states() {
      const states = new Set();
      this.$store.state.posts.forEach((post) =>
        states.add(post.acf.address.state)
      );
      return Array.from(states);
    },
  },

这会返回两个单独的数组,countriesstates,我如何按国家/地区组织数组,然后按该国家/地区的州组织?


【问题讨论】:

  • 你想要什么格式的数据?
  • 到目前为止,嵌套数组似乎可以完美运行!我不知道如何在相应的州后面加上他们的国家。

标签: javascript json vue.js vuejs2 vue-component


【解决方案1】:

您可以使用一个字典,其键是国家名称,值是状态数组:

computed: {
  dictionary() {
    const dictionary = {};
    this.$store.state.posts.forEach(post => {
      const c = post.acf.address.country;
      const s = post.acf.address.state;
      dictionary[c] = dictionary[c] || [];
      !dictionary[c].includes(s) && dictionary[c].push(s);
    });
    return dictionary;
  }
}

处理重复:如果&&/push 语句看起来很奇怪,它就像一个简短的if 语句测试状态是否已经在列表中,如果不是则只到达推送语句

【讨论】:

  • 除非我误解了你,否则这很容易成为你所要求的最好方法。嵌套的状态数组,你可以v-for它来获取国家和州名。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2016-03-19
  • 1970-01-01
  • 2020-02-27
相关资源
最近更新 更多