背景
在现实开发环境下,会遇到这样的场景:
后端返回的字段名与组件中需要的字段名不一致;
当然,最快的解决方法就是让后端改字段名;
考虑到特殊情况,我们前端还是要留一手,不求人!!!
后端返回数据结构如下:
tableData: [
{
name: '老王',
age: '18'
},
{
name: '李四',
age: '21'
},
{
name: '张三',
age: '16'
}
]
我们需要的数据结构如下:
tableData: [
{
lable: '老王',
age: '18'
},
{
lable: '李四',
age: '21'
},
{
lable: '张三',
age: '16'
}
]
解决方案
// oldName => 需要被替换的属性名(字段名); newName => 新属性名(字段名)
const a = JSON.stringify(this.tableData).replace(/oldName/g, 'newName')
this.tableData = JSON.parse(a);