Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex:

posts:[
  {
   id: 1;
   title: "Place",
   acf: {
     address: {
       state: "Arkansas",
       country: "United States"
     },
   },
  },
  {
   id: 2;
   title: "Place 2",
   acf: {
     address: {
       state: "Arkansas",
       country: "United States"
     },
   },
  },
  {
   id: 3;
   title: "Place 3",
   acf: {
     address: {
       state: "Arkansas",
       country: "United States"
     },
   },
  },
  {
   id: 4;
   title: "Place 4",
   acf: {
     address: {
       state: "Missouri",
       country: "United States"
     },
   },
  },
  {
   id: 5;
   title: "Place 5",
   acf: {
     address: {
       state: "Johor",
       country: "Malaysia"
     },
   },
  },
]

The challenge now is to organize this data in a v-for loop with the following structure (showing United States first, followed by alphabetical order):

  • United States
    • Arkansas
      • Place
      • Place 2
      • Place 3
    • Missouri
      • Place 4
  • Malaysia
    • Johor
      • Place 5

To achieve this hierarchy, it seems like I should use a computed function, but I'm struggling to implement the structure of:

- Country
  - State 
    - Place

Answer №1

Create a structured dictionary by nesting objects:

computed: {
  structuredDictionary() {
    const structuredDictionary = {};
    this.$store.state.posts.forEach(post => {
      const country = post.acf.address.country;
      const state = post.acf.address.state;
      const place = post.title;
      structuredDictionary[country] = structuredDictionary[country] || {};
      structuredDictionary[country][state] = structuredDictionary[country][state] || [];
      structuredDictionary[country][state].push(place);
    });
    return structuredDictionary;
  }
}

The main object holds country names as keys. Each country contains an inner object with state names as keys and an array of places as values.

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

What is the best way to input variables into json values? [JavaScript]

let countryCode; let countryName; $(window).on("load", function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" }).done(function (json) { countryCode = json.country_code; $(function () { $.ajax({ url: "URL_THAT_RETURNS_JSON" ...

Adjust padding of elements based on scrolling movements

Currently, I am attempting to adjust the padding of a specific element based on how far down the page the user scrolls. Ideally, as the user scrolls further down the page, the padding will increase, and as they scroll back up, the padding will decrease. H ...

unable to effectively test promises with stubs using nodejs mocha

Currently, I am facing a couple of challenges when attempting to perform unit testing on promises using Mocha. 1) The main issue I encounter is an Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Prom ...

Using Angular to open a modal by invoking the href function

Current Project Context I am currently following a tutorial on CRUD operations with DataTables, but I am using Asp.Net WebApi with Angular for this project. At step 9 of the tutorial, it introduces partial views for pop-up windows. However, instead of us ...

Components in React are unable to be accessed

I'm a complete beginner when it comes to React and I'm facing issues with organizing my components into separate files. The error message I encounter is: ERROR in ./src/App.js 5:0-34 Module not found: Error: You attempted to import /components/ ...

Ways to make an AngularJS Expression show an empty value

Consider the following HTML snippet: <p>{{ booleanVariable ? "The variable is true!" : "" }}</p> In case 'booleanVariable' evaluates to false, the expression should display nothing and the <p></p> tags should not be show ...

Having trouble with Google Charts? Despite receiving json output, the graph still isn't showing up

After much effort, I have successfully gotten my php code to work with the Google Charts column chart. When I execute my php script, it outputs the following data: {"cols":[{"id":"id","label":"second","type":"number"}, {"id":"threads","label":"threads","t ...

Elements are automatically removed from default.vue once they have been compiled in Nuxt

Looking to add a header in my Nuxt application within Nuxt/layouts/default.vue <template> <div> <Navigation/> <Nuxt /> </div> </template> But the code: <template> <Nuxt /> </template> ...

Tips for uploading multiple files using django-rest-framework

When trying to upload files using django-rest-frame, I encountered an issue where only the last file uploaded would be saved. How can I ensure that all files are saved? Software versions: Python 3.6.2 Django 2.2.3 djangorestframework 3.10.1 Code snippet: ...

What is the best way to initiate an onload event from a script embedded within a jquery plugin?

Currently, I am in the process of developing a jQuery plugin. One issue that I have encountered involves a script tag being dynamically added for LivePerson.com. The script is supposed to trigger an onLoad function specified in the configuration. However, ...

Alter the hue of a component upon being clicked

Seeking help to modify the color of my menu elements upon clicking on the "center" or "right" containers (reverting back when clicked again). Currently, the three lines in my menu are white, but I desire them to turn red when either of these containers is ...

"Automating the process of toggling the edit mode of a contenteditable element – how is

Is there a specific event I can use to programmatically start or stop editing a contenteditable element, similar to when the user focuses or blurs it? I have tried using .focus(), .click(), and even setting the selection to its content, but none of them se ...

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

Can Acumatica support the loading of external JavaScript files or libraries?

I am currently developing a new Acumatica screen for our company that will involve integrating javascript code to retrieve and display a map object (from ESRI). The challenge is that this code necessitates an external .js file which the javascript code it ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

What is the reason behind getElementsByClassName not functioning while getElementById is working perfectly?

The initial code snippet is not functioning correctly DN.onkeyup = DN.onkeypress = function(){ var div = document.getElementById("DN").value document.document.getElementsByClassName("options-parameters-input").style.fontSize = div; } #one{ heigh ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...

Annoying jQuery animation error: struggling to animate smoothly and revert back. Callback function conundrum?!

I'm completely lost with what I have accomplished. My goal was to create an animation where an element slides in from a certain position and then slides back when another element is clicked. To achieve this, I included the second event within the call ...

Executing Selenium WebDriver to interact with a hidden element

Hello, I am interested in learning how to interact with hidden elements and disable them using Selenium WebDriver. I've managed to achieve this with Selenium 1 by using the following code: selenium.click(id="idOfHiddenField"); Unfortunately, this a ...

Socket.io encounters emitting issue within express app.post function

I am working on integrating an express application with a frontend React application using socket connections. My goal is to trigger an event on the connected socket whenever a post request containing JSON data is sent to my server. However, I am facing a ...