当后台传过来的数据名字不是title,key时需要将相应的值赋给它们,但是树形结构中还有几层children,所以修改时需要遍历。
方法:
array就是你的数据。
getValueFromOtherkey这是一个对象,意义是你需要新增的值,值依据于你当前数组内的某一项;里面每一项的键是你要新增的键名,里面的值是你要新增的值对应的当前数组项的那个字段的键名。
setKey,这也是一个对象,意义是你要新增的自己传入的值,这个比较好理解,键值对就是你传入的键值对
function setAttr(array, getValueFromOtherkey,setKey) {
array.forEach((item) => {
for (const key in getValueFromOtherkey) {
item[key] = item[getValueFromOtherkey[key]]
}
for(const myKey in setKey){
item[myKey]=setKey[myKey]
}
if (item.children && Array.isArray(item.children) && item.children.length) {
return setAttr(item.children,getValueFromOtherkey,setKey)
}
})
return array
}
console.log(setAttr(array, { title: 'name', key: 'id' },{scopedSlots:{title:'custom'}}))
在获取到数据后可以调用该方法,对获取到的数组数据进行修改。
//this.categoryList是通过后台获取到的值
this.categoryList = this.setAttr(
this.categoryList,
{ title: "category", key: "id" },
{ scopedSlots: { title: "action" } }
);