Manipulate API Response to display organized list

放肆的年华 提交于 2020-12-13 03:09:52

问题


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):

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

It is my understanding I should be using a computed function for this, but cannot get the hierarchy of:

- Country
  - State 
    - Place


回答1:


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.



来源:https://stackoverflow.com/questions/65206040/manipulate-api-response-to-display-organized-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!