1. 程式人生 > 實用技巧 >vue提取json中,某一個元素的值,並且用value組成一個數組

vue提取json中,某一個元素的值,並且用value組成一個數組

這個是瞎搗鼓出來的。需要是做一個下拉select選擇框,因為用的是vant,所以程式碼是這樣的

<van-field
            readonly
            clickable
            name="areaCode"
            :value="value"
            label="區域編碼"
            placeholder="點選選擇區域編碼"
            @click="areaCode = true"
            />
            <van-popup v-model="areaCode" position="bottom">
            <van-picker
                show
-toolbar :columns="columns" @confirm="onConfirm" @cancel="areaCode = false" /> </van-popup> <van-field v-model="equipmentCode" name="equipmentCode" label="裝置編碼" placeholder
="請輸入裝置編碼" :rules="[{ required: true, message: '請輸入裝置編碼' }]" />

後臺返回了一個數據,一開始資料是這樣的,我需要先把areaCode的value值提取出來,放到columns組成一個數組

[{"areaCode":"A001","areaName":"海淀區","id":1,"createdBy":"test","createTime":"2020-10-26 15:06:45","modifyBy":"test","modifyTime":"2020-10-26 15:26:34","isRemoved":"N"},{"areaCode":"A002","areaName":"朝陽區","id":2,"createdBy":"test","createTime":"2020-10-26 15:27:41","modifyBy":"test","modifyTime":"2020-10-26 15:27:52","isRemoved":"N"},{"areaCode":"A003","areaName":"通州區","id":4,"createdBy":"test","createTime":"2020-10-26 15:46:22","modifyBy":"test","modifyTime":"2020-10-26 15:46:22","isRemoved":"N"},{"areaCode":"A004","areaName":"昌平區","id":5,"createdBy":"test","createTime":"2020-10-26 15:46:33","modifyBy":"test","modifyTime":"2020-10-26 15:46:33","isRemoved":"N"},{"areaCode":"A005","areaName":"延慶區","id":6,"createdBy":"test","createTime":"2020-10-26 15:46:47","modifyBy":"test","modifyTime":"2020-10-26 15:46:47","isRemoved":"N"}]

我先提取了一下areacode這個屬性,變成

rs.result.map(o=>{return{areaCode:o.areaCode}});
//控制檯打印出來的json變成
[{"areaCode":"A001"},{"areaCode":"A002"},{"areaCode":"A003"},{"areaCode":"A004"},{"areaCode":"A005"}]

因為不需要areacode這個key'名字,我又提取了一下變成

rs.result.map(o=>{return[o.areaCode]})
//控制檯值變成
[["A001"],["A002"],["A003"],["A004"],["A005"]]

但是還是不符合vant下拉框資料格式,又把獲取的value值轉換了一下才可以

rs.result.map(o=>{return[o.areaCode].toString()});
//控制檯json變成
["A001","A002","A003","A004","A005"]
符合要求了

說了這麼多,其實最根本的,就那麼一行程式碼,,,就是看需要啥樣資料,就用哪個把