Append States to Countries from API Data

Viewed 62

I have an API that is returning data in the following format:

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

Right now, I'm getting the list of countries and states with the following computed code:

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);
    },
  },

This returns two separate arrays, countries and states, how can I organize the array by country, then states within that country?


1 Answers

You could use a dictionary whose key is the country name and value is an array of states:

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;
  }
}

Handling duplicates: If the &&/push statement looks strange, it's like a short if statement testing whether the state is in the list already, and only reaches the push statement if not

Related