要更改键名的数据
objData=[
{
text:'1',
id:'0',
obj:[
{
text:'1-1',
id:'11'
},{
text:'1-2',
id:'12'
}
]
},{
text:'2',
id:'1',
obj:[
{
text:'2-1',
id:'21'
},{
text:'2-2',
id:'22'
}
]
}
]
将obj更改为children,id改为value,text改为name
renameObjectKey(oldObj) { // 对键名进行替换 第一层数组对象 oldObj为数组对象
const userRelations = {
text: "name",
id: "value",
obj: "children"
};
let arr = [];
oldObj.forEach((item) => {
let obj = {};
for(let i in item){
if(i == 'dicData'){
obj = this.renameObjectKeyTow(item)
}
}
Object.keys(item).forEach((value) => { // 替换第一层数组对象键名
obj[userRelations[value]] = item[value];
});
arr.push(obj);
})
return arr
},
renameObjectKeyTow(oldObj){ // 第二层数组对象
const userRelations = {
text: "name",
id: "value",
};
let arr = [];
oldObj.obj.forEach((item) => {
let obj = {};
Object.keys(item).forEach((value) => {
obj[userRelations[value]] = item[value];
});
arr.push(obj);
})
oldObj.obj= arr
return oldObj;
},
// 或者直接在对象里添加需要的元素将值赋值上去
renameObjectKey(obj){
obj.forEach(item => {
item.text=item.name
item.value=item.id
if (item.children && item.children.length > 0) {
this.renameObjectKey(item.children);
}
});
return obj
},
使用时
let a = this.renameObjectKey(this.objData)
// a就是处理后的双重数组对象