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

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Streaming the request body in NodeJS using ExpressJS without buffering

Looking for a solution to process requests with no specified content-type as binary files. const app = express(); app.use(bodyParser.raw({type: (req) => !req.headers['content-type'], limit: '500mb' })); Some of these files can be ...

Utilizing the import feature for structuring the routes folder in Express with Node.js

Recently, I made the switch to using ECMAScript (ES6) for my NodeJS Rest API with Express, and I've encountered a few challenges when working with the new keyword import In the past, I would organize my routes folder like this: Let's imagine th ...

Is there a way for me to incorporate a feature that verifies whether an email address is already registered before allowing the person to sign up?

I am currently working with Node.js, express.js, mongoose, and pug to develop a registration/login system. I have successfully stored the name and email in a mongoose database with specified schema for these fields. The data is sent from a pug page via a p ...

Tips for quickly rendering over 10,000 items with React and Flux

What is the most efficient way to render a large number of items in React? Imagine creating a checkbox list with over 10,000 dynamically generated checkbox items. I have a store that holds all the items and serves as the state for the checkbox list. Whe ...

Activate automatic click or force trigger JavaScript function

In the MVC view I am working with, there is a form that allows for file submission. //Submit file <% using (Html.BeginForm("MethodName","ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})) { %> <input type=" ...

Experiencing difficulties transferring information between Components

How can I successfully pass an Object Array generated by a method in one component to another component? I've attempted using props, but it seems like my understanding of how props function may be lacking. <template> <div class="media-b ...

Utilizing Query Data Source in ASP.NET MVC for Enhanced JQuery DataTables Experience

Overview I am venturing into ASP.NET from ColdFusion and seeking guidance on replicating a similar technology in MVC 5. My current approach involves running a query in a CFC to populate a DataTable, where the results are then arranged in JSON format and ...

Retrieving data from a JSON file depending on the selection made by the user in a dropdown menu

In my project, I have a JSON file named countries.json that contains country and regional information. Users are required to select a country using a Python-generated dropdown list from this file. However, due to the backend nature of Python, I am unable t ...

Aggregate values through an onclick event using a get request and iterate through each using

I am struggling to accumulate values obtained from a json get request using jQuery. The problem is that the values keep getting replaced instead of being added up in the variable total. Can someone please guide me on how to properly sum up the values with ...

Troubleshooting problem with HTML5 history mode in Vue Router v4 when reloading the page or accessing directly

I have set up a demonstration of Vue3 on my webserver in a subdirectory: https://tokant.com/vue-router-transition-v2/ Clicking on the different navigation links functions correctly, and refreshing the browser on home and about also works fine. However, wh ...

What is the process behind Stackoverflow's "Congratulations, you've earned a new badge" popup window?

Possible Duplicates: Custom notify box similar to StackOverflow Creating popup message like StackOverflow How does StackOverflow implement the "You earned a new badge" window? (the orange one that pops up at the top of the screen, I believe it&ap ...

The Angular UI Bootstrap Datepicker fails to appear on top of the Bootstrap Modal

I'm currently working on an Angular app that utilizes UI Bootstrap. Within my app, I have a modal containing a Datepicker at the bottom. However, I've encountered an issue where the Datepicker remains confined within the modal when expanded. I at ...

How can you integrate jquery ajax in WordPress?

Recently, I started learning about jquery and have been following a tutorial on creating instant search using jquery. The tutorial can be found here. Now, I am trying to implement this on my WordPress site, but it seems like things work differently when d ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...

Error encountered due to an extra escape character in JSON causing the API call to fail

I'm currently working on making an API call to a service running locally. The service requires the POST request to contain JSON data in this format: {"tool" : "name", "version" : "1", "payload" : "{"branch" : "main"}" These parameters are members of ...

Error: Unable to assign the 'schedule' property to a null value

I'm currently developing a scheduling application using React.js and have implemented a draggable scheduling feature for users to indicate their availability. Everything seems to be working smoothly, except for one pesky error message: TypeError: Cann ...

How can I incorporate images into my Vue Select dropdown?

Currently, I am using the vue-select component to display dropdowns on my website. These dropdowns are populated with data provided through the :options attribute. Specifically, I am working on implementing a credit card dropdown and would like to includ ...

Group JSON data in Python based on the individuals' last names

Hey there, I'm new to this. How can I manipulate a Json data in Python to create a new format where the last name is used as the key and the value contains the total count of people with the same last name, along with their respective age and departme ...

Python encounters issues when parsing JSON file

I have a JSON file (referred to as k in my script) with nested levels that I'm trying to analyze, but I'm encountering a confusing error. Below is my current code: for i in k: if 'pens' in k[i]: print i+" "+str(k[i][&apo ...