export const difficulty = [
{
value: 1,
label:'简单'
},
{
value:2,
label:'一般'
},
{
value:3,
label:'困难'
}
]
接下来,上面代码形式进行转换:使用reduce
const f = arr=>arr.reduce((acc,item)=>({...acc,[item.value] : item.label}),{ })
这个是转换成的格式:
{1: "简单", 2: "一般", 3: "困难"}
第一种:
const difficultyFormat = diffculty.reduce((acc,item)=>({...acc,[item.value] : item.label}),{ })
console.log(difficultyFormat) // {1: "简单", 2: "一般", 3: "困难"}
// 获取列表
async choiceList () {
try {
// const res = await choice(this.pageParams, this.form)
const res = await choice({ ...this.pageParams, ...this.form })
console.log('精选题库列表', res)
this.list = this.format(res.data.items) //放这段代码 主要是这一行
//e就是res.data.items e的每一项的difficulty都做了转换 然后页面上直接用就行(平时咋渲染就咋渲染)
this.counts = res.data.counts
} catch (err) {
console.log(err)
}
}
format (e) {
console.log(e)
e.forEach(item => {
item.difficulty = difficultyFormat [item.difficulty]
// item.difficulty 是 1 2 3 字符串 然后转一下,变成 简单,一般,困难
//每一个对象里面的属性是这样的: difficulty: "1" difficulty: "2" difficulty: "3"
//difficultyFormat.1/2/3 {xxxx: 'value'} {1/2/3 : '简单'}
})
// difficultyFormat.name = '张三'
//{1: "简单", 2: "一般", 3: "困难", name: "张三"}
return e
},
第二种:
methods里面
diff(res){
return diff[res]
}
页面上使用的时候: {{diff(xxxxxxxxx)}}
接口返回的数据,difficulty:'1' xxx这个位置就把1渲染上去,{1: "简单", 2: "一般", 3: "困难"}这种形式,1就是键,对象.键 就能拿到对应的值 ----简单 一般 困难