Reputation: 97
I'm making an API call for a list of properties that are unorganized from the API. The data from the API is stored in vuex looks like this:
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"
},
},
},
]
I need to organize the data to display in a v-for loop in the following format (with the United States first, then alphabetical):
It is my understanding I should be using a computed function for this, but cannot get the hierarchy of:
- Country
- State
- Place
Upvotes: 1
Views: 30
Reputation: 63099
You could make a nested dictionary:
computed: {
dictionary() {
const dictionary = {};
this.$store.state.posts.forEach(post => {
const c = post.acf.address.country;
const s = post.acf.address.state;
const t = post.title;
dictionary[c] = dictionary[c] || {};
dictionary[c][s] = dictionary[c][s] || [];
dictionary[c][s].push(t);
});
return dictionary;
}
}
The outer object has country names for keys. Each country value is itself a similar object with state names as keys. The state value is an array of places.
Upvotes: 1