描述:
有时候我们请求接口得到的数据并不是我们想要的格式,单又不想麻烦后端开发人员更改,让其误以为我们很菜时,这时候就需要我们前端进行转换一下,得到我们像要的数据格式,以彰显我们前端大佬的技术水平了。
来看个例子,如下所示数据:
data: [
{
achieveSum: null
checkState: 1
companyId: null
companyName: null
directory: null
directoryName: "第一章 哇哈哈"
},
directoryVoList: [
achieveSum: null
checkState: 1
companyId: 10
companyName: "哇哈哈"
directory: 12
directoryName: "第一章 集团简介"
]
]
我们可以看到这是一个二维数组 组成的一个json数据对象,我想替换其中的字段directoryName
和 字段directoryVoList
为label
和children
字段该怎么办呢?
首先:我们很清楚这些字段都是字符串,那么想要全部替换的话嘴贱单的方法就是利用字符串的replace
方法和/ /g
正则表达式的全局匹配了。
知道方法后,就可以写代码了。来看下面代码:
getTrainData({
fatherId: this.fatherId,
}).then((res) => {
console.log(res)
res = JSON.parse(JSON.stringify(res).replace(/directoryName/g, "label"))
res = JSON.parse(JSON.stringify(res).replace(/directoryVoList/g, "children"))
this.dataTree = res
console.log(res)
}).catch((err) => {
this.$message.error('获取数据失败,请稍后再试')
})