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

Having trouble importing the named export `{module}` from a non-ECMAScript module with TipTap and Nuxt?

I'm using TipTap with Nuxt and running into some issues that I can't seem to resolve. Despite following suggestions from the repository's issues, I keep encountering these specific errors: ERROR in /Volumes/Projects/nuxt/candy-hub-lerna/no ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

How can I extract values from an array stored in an external text file using Jquery?

I'm attempting to retrieve an error message from an external file called errors.txt. The contents of errors.txt are as follows: var data = { 'errors': [{ "code": "9999", "message": { row: 1, ...

Unpacking the information in React

My goal is to destructure coinsData so I can access the id globally and iterate through the data elsewhere. However, I am facing an issue with TypeScript on exporting CoinProvider: Type '({ children }: { children?: ReactNode; }) => void' is no ...

Warning: Angular.js encountered a max of 10 $digest() iterations while iterating through array slices. Operation aborted

JSbin: http://jsbin.com/oxugef/1/edit I am attempting to slice an array into smaller subarrays and iterate through them in order to create a table of divs that are evenly divided. Unfortunately, there seems to be an issue where I am unknowingly overwritin ...

Identify the credit card as either American Express or American Express Corporate

My JavaScript code can successfully detect credit card types, but I have encountered an issue. I am unable to differentiate between American Express and American Express Corporate cards. Is there a way to distinguish them or is it impossible to identify wh ...

Retrieve the element referred to as $el within a computed property

When attempting to retrieve this.$el.offsetTop within a computed property, the following error occurs: Cannot read property 'offsetTop' of undefined Is there a way to access the component's offsetTop in a computed method? If not, what is t ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

Selecting an object from JSON data with Angular using $routeParams

I am attempting to showcase information from a JSON file that is structured like this: [ { "category":"category1", "link":"category1", "expand":false, "keyword":"category1, category1 online, category1 something" }, { "category":" ...

What is the proper way to serialize an ISODate object using Gson?

I have extracted this JSON data from a MongoDB database: { "_id" : "123", "ip" : "127.0.0.1", "start_time" : ISODate("2016-12-28T17:16:08.283Z"), "end_ocr_time" : ISODate("2016-12-28T17:16:11.652Z"), "end_addr_time" : ISODate("2016-12-28T17:16:1 ...

Internet Explorer is requesting to download my JSON response, while other browsers are functioning normally

Through my research, it seems that the problem lies in the way the headers are set for the response. The application is built on the Zend framework, and here are the specific headers that are being set (this pertains to a file upload): $response -> ...

What is the best way to merge two tables together using the server-side JQuery Datatable plugin?

I recently came across an amazing example of a server-side ColdFusion jQuery datatable on this website: Check it out here However, I am facing an issue with adding a second table in the lookup. Specifically, while the primary table lists location_id, I al ...

"Exploring the wonders of hosting Vue js Single Page

Can anyone recommend a user-friendly tutorial for hosting a vue.js SPA application? I've already uploaded the entire project to the server using Filezilla, but I forgot to run npm run build before hosting it. Is it possible to run npm run build locall ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

Can lazy loading be implemented for the video tag using JavaScript?

Currently, I am in the process of working on a project that entails incorporating three videos onto the homepage. However, loading them simultaneously is causing a significant decrease in load time. In addition, I prefer to utilize the <video/> tag ...

How can I update a specific element within an array of objects in JavaScript based on its reference rather than its index position?

I am dealing with multiple arrays of objects x=[ {a:1}, {b:2}, {c:3}, {d:4} ] y=[ {e:5}, {f:6}, {g:7}, {h:8} ] (etc) and I have a list of references pointing to the objects I need to replace. Instead of having an index into the array, I hold reference ...

What is the method for retrieving the name of a canceled file?

When a user clicks on the "Cancel" button during an upload, I am attempting to retrieve the filename of the file that was canceled. However, it seems like the current method I am using (var image_file_name) is not successfully retrieving the name of the ca ...

Switching jQuery on various sections of a webpage

In my attempt to replicate the functionality of Facebook's Like button, I have encountered a challenge regarding where exactly to click in order to change the button state. When the button is not liked yet, users should be able to click anywhere on t ...

Tips for sending parameters using arrow functions within ReactJS hooks

I've recently started working with ReactJS and I'm a bit confused about how to pass parameters using arrow functions. I attempted to use .bind() in order to bind the value so it can be used in the function, but unfortunately that didn't work ...

Assistance needed for disabled JavaScript

I'm currently working on a small application where I need to display some text wrapped in 3 divs. The goal is to only show one div at a time and provide users with prev and next buttons to switch between them. However, when JavaScript is disabled, I w ...