Add United States as an additional attribute to the countries retrieved from the API

I am working with an API that provides data in a specific format:

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

Currently, I have a computed code block to extract the list of countries and 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);
    },
  },

The above script generates separate arrays for countries and states. How can I reorganize these arrays by country first, then by states within each country?


Answer №1

To organize the data efficiently, consider using a dictionary with country names as keys and arrays of states as values:

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

Dealing with duplicates: If the &&/push syntax is unfamiliar, it acts like a compact if statement to check if the state is already in the list before adding it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue Testing Library with Nuxt.js: A Beginner's Guide

Looking to incorporate Vue Testing Library into my Nuxt.js project. Encountered an error right after installation, where running a test results in the following message: 'vue-cli-service' is not recognized as an internal or external command, op ...

What is the appropriate Java object representation for this JSON data?

{"userId":"vincent","favTracks":{"favourite":"15","unFavourite":"121"}} What Java data structure could represent the information in the given JSON String? ...

What is the best method for storing objects in Firebase in order to easily rearrange them at a later time?

My list looks something like this: {"ids": [ { "id1": { "name": "name1", "lastname": "lastname1" } }, { "id2": { "name": "name2", "lastname": "lastname2" } }, { "id3": { "name": "name3", "l ...

What is the best way to extract URL query parameters and store them in a MySQL database using Node.js and Express

I am working on a project where I need to store specific information like names and widths from the URL query into my MySQL database. The format of the URL query should resemble this: /register?name=XXXX&width=###.### However, I seem to be facing ch ...

Prepend a fixed header to the filter

Imagine this (simplified) JSON data: [ { "type": "foo", "name": "test_1" }, { "type": "bar", "name": "test_2" }, { & ...

Understanding @@iterator in JavaScript: An in-depth look

Can someone shed some light on the mysterious @@iterator? It keeps popping up in tutorials but no one seems to provide a clear explanation of what it actually is. Is it a symbol literal or something else entirely? ...

Potential Cross-Origin Resource Sharing (CORS) problem arises when integrating Node Express with an Ionic

Currently, I have an Ionic application that communicates with a Node Express application using Restangular. Everything works smoothly when the Node Express server is configured to use HTTP. On the Ionic app side: RestangularProvider.setBaseUrl('http ...

I'm having trouble with my controller - not sure what the problem is

My controller seems to be malfunctioning. I have created a controller but it is not functioning properly. Even though I have reviewed it multiple times, the issue persists. Could someone please assist me with this problem? Angular Code var myPanelSearch ...

Validation of JSON + ld structured data using webmaster tools

I have implemented Structured Data Markup on a product page using json + ld and placed the script tags in the header section. There are two lines marking the script section. The JSON segment validates properly on , but it does not display content when val ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

What is the significance of &(0,1) in Jolt data conversion?

Check out this example of converting prefix json into nested json by clicking here (Convert 'prefix soup', to nested data item) One interesting string found in the translation is "rating-*": "SecondaryRatings.&(0,1)" I have noticed that * ...

Ways to verify if the current date exists within a TypeScript date array

I am trying to find a way in typescript to check if the current date is included in a given array of dates. However, even after using the code below, it still returns false even when the current date should be present within the array. Can anyone please pr ...

Using the max-width property with Semantic UI Dropdown in ReactJS

I'm struggling to determine how to adjust the max-width of the Dropdown element in ReactJS. I attempted the following: .Menu Dropdown { max-width: 5rem !important; } Unfortunately, this did not work as expected. The dropdowns are taking up too m ...

What strategies can I use to dynamically update the .active class in jquery so it doesn't only target the initial one?

Utilizing bootstrap for tab-fade functionality has been successful so far. However, I am facing an issue when trying to select multiple active classes instead of just one. My current JQuery code only changes the text in the first element with the "active" ...

Vue.Js allows developers to easily set a default selected value in a select dropdown menu

Having trouble with getting the default selected value using select in VueJs. I've attempted two different approaches: Using id and v-model fields in the select like this: <select v-model="sort_brand" id="sort-brand" class="form-control"> ...

Can a robust web application be developed using Kotlin in Node.js?

With the recent release of Kotlin 1.1, it is now possible to compile Kotlin projects into JavaScript as a target, allowing for full JavaScript compilation. Can a Node.js application, like an express webserver, be developed entirely using Kotlin code? As s ...

Attention: Invalid JSON response detected for table ID "seo_editor_product" in DataTables

Currently, I am using Xampp along with MariaDB 10.2.7 for my project. Recently, I added an SEO module that utilizes JSON and encountered the following error message. A critical Error has been detected: You have a SQL syntax error; please refer to the us ...

Securing the Firebase Admin SDK JSON file within a NextJS project for optimal protection

I'm currently working on a NextJS app that uses the Firebase Admin SDK, but I'm unsure of where to securely store the JSON file containing all the keys. It seems that integrating secret keys in JSON files with an .env.local file is not possible. ...

Troubleshooting: React.js State not updating properly on forms

New to React and facing a challenge with changing the state of form inputs. Here's what I'm trying to do: constructor(props) { super(props); this.state = { pwd:'', email:'', value:'' ...

What do you notice about interactions involving 'input type=text' in HTML and JavaScript?

When a new binding is created for the value property on an input, any manual modifications by the user no longer update the value. What happens when the binding is altered? Does regular user interaction involve key press listeners? I've modified the ...