数组转对象
Formily接收一个类似于
{
"type": "object",
"properties": {
"tabs": {
"key": "tabs",
"type": "object",
"name": "tabs",
"x-component": "tab",
"x-component-props": {
"defaultActiveKey": "tab-2"
},
"properties": {
"tab-1": {
"key": "tab-1",
"type": "object",
"name": "tab-1",
"x-component": "tabpane",
"x-component-props": {
"tab": "选项1"
},
"properties": {
"a1": {
"key": "a1",
"type": "string",
"name": "a1",
"title": "字段1",
"required": true,
"x-component": "input"
}
}
},
"tab-2": {
"key": "tab-2",
"type": "object",
"name": "tab-2",
"x-component": "tabpane",
"x-component-props": {
"tab": "选项2"
},
"properties": {
"a2": {
"key": "a2",
"type": "string",
"name": "a2",
"title": "字段2",
"required": true,
"x-component": "input"
}
}
}
}
}
}
}
而我的基础数据格式为
坑的代码:
let newPanes = panes.map(item => {
let newQues = transQuestion(item.content) // 转换conent里面的数据格式,让其支持formily
let panekey = `${item.objectKey}` // 就是选项卡名称
return {
[panekey]: {
'type': "object",
'name': item.title,
"x-component": "tabpane",
"x-component-props": {
"tab": item.title
},
'properties': {
...newQues
}
}
}
})
获得这样的数据
现在只要把数组里的对象映射到properties里面就可以
类似与
const schema = {
type: 'object',
properties: {
tabs: {
type: "object",
name: "tabs",
"x-component": "tab",
"x-component-props": {
defaultActiveKey: "tab1"
},
properties: {
...newPanes
}
}
}
};
但是这样映射会多个下标,数组里可以直接塞对象是因为数组的下标就是key
就会陷入如何将一个数组对象变成普通对象的误区
正确做法:
直接创建一个空对象,给空对象赋值
let newObj = {}
panes.map(item => {
let newQues = transQuestion(item.content) // 转换conent里面的数据格式,让其支持formily
let panekey = `${item.objectKey}` // 选项卡名称
newObj[panekey] = {
'type': "object",
'name': item.title,
"x-component": "tabpane",
"x-component-props": {
"tab": item.title
},
'properties': {
...newQues
}
}
})
正确数据解构,也是上述错误想法中想要转换的数据结构