数组与对象之间的纠葛

数组转对象

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
      }
    }
  })

正确数据解构,也是上述错误想法中想要转换的数据结构
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值