iT邦幫忙

0

js match object key? (vuex)

  • 分享至 

  • twitterImage

假設我取得一個 object 為 this.$store.state.v.list

this.$store.state.v.list:

[{
        "value": 1,
        "label": "安"
      },
      {
        "value": 2,
        "label": "補"
      },
      {
        "value": 3,
        "label": "牽"
      }]

假設我使用 valueId 可以取得 value

當取得 value 為 2 則顯示「補」

this.$store.state.v.list.value[valueId].label

但以上發生錯誤
因為 object 是從 0 開始
但我要他 match 的是 value
請問能怎麼做?(能否給個思路)
https://imgur.com/BLaTvwS

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
dragonH
iT邦超人 5 級 ‧ 2020-03-27 14:02:09
最佳解答

你的 data 應該是長這樣吧

      [{
        "value": 1,
        "label": "安"
      },
      {
        "value": 2,
        "label": "補"
      },
      {
        "value": 3,
        "label": "牽"
      }]

mapindexOf

或直接 filter

應該可以達到你的目的

看更多先前的回應...收起先前的回應...
火爆浪子 iT邦研究生 1 級 ‧ 2020-03-27 14:15:30 檢舉

解決了

let renderLabel = ``;
      let arr = this.$store.state.v.list;
      Object.keys(arr).map(key => {
        if (arr[key].value === valueId) {
          renderLabel = arr[key].label;
        }
      });
      return renderLabel;
火爆浪子 iT邦研究生 1 級 ‧ 2020-03-27 14:16:22 檢舉

只是這樣好像假設有五筆
這個 func 就會重複二十五次

dragonH iT邦超人 5 級 ‧ 2020-03-27 14:20:36 檢舉

codepen

可以用 filter 就好

火爆浪子 iT邦研究生 1 級 ‧ 2020-03-27 14:21:55 檢舉

感謝!

我剛剛就在想說filter 應該比較簡單XD
this.$store.state.v.list.filter(el => el.value===valueID)[0].label

dragonH iT邦超人 5 級 ‧ 2020-03-27 14:24:15 檢舉

對阿XD /images/emoticon/emoticon07.gif

froce iT邦大師 1 級 ‧ 2020-03-27 16:51:20 檢舉

呃,看懂題目比較難

我要發表回答

立即登入回答