亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 API 數據中的州添加到國家/地區

將 API 數據中的州添加到國家/地區

吃雞游戲 2023-10-14 10:00:28
我有一個 API,它以以下格式返回數據:[ {  "id": 12,  "acf": {    "address": {      "city": "Bandar Penawar",      "state": "Johor",      "country": "Malaysia",   } }, {  "id": 16,  "acf": {    "address": {      "city": "Some City",      "state": "Arizona",      "country": "United 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);    },  },這將返回兩個單獨的數組,countries并且states,如何按國家/地區以及該國家/地區內的州組織數組?
查看完整描述

1 回答

?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

您可以使用一個字典,其鍵是國家/地區名稱,值是州數組:


computed: {

  dictionary() {

    const dictionary = {};

    this.$store.state.posts.forEach(post => {

      const c = post.acf.address.country;

      const s = post.acf.address.state;

      dictionary[c] = dictionary[c] || [];

      !dictionary[c].includes(s) && dictionary[c].push(s);

    });

    return dictionary;

  }

}

處理重復:如果&&/push語句看起來很奇怪,那么它就像一個簡短的if語句,測試狀態是否已經在列表中,如果不在則只到達推送語句


查看完整回答
反對 回復 2023-10-14
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號