数组对象重组

小太阳大晴天
  • 69

es6操作数组对象

这是原始数据格式
const arr = [
  {
    "id": 1,
    "name": "田径",
    "upid": 0,
    "code": "",
    "level": "",
    "child": [{
      "id": 9,
        "name": "田径",
        "upid": 1,
        "code": "20006",
        "level": "B"
      }]
   }, 
   {
        "id": 2,
        "name": "球类运动",
        "upid": 0,
        "code": "",
        "level": "",
        "child": [{
            "id": 10,
            "name": "排球",
            "upid": 2,
            "code": "20007",
            "level": "B"
        }, {
            "id": 11,
            "name": "网球",
            "upid": 2,
            "code": "20008",
            "level": "B"
        }, {
            "id": 12,
            "name": "棒球",
            "upid": 2,
            "code": "20009",
            "level": "B"
        }, {
            "id": 13,
            "name": "橄榄球",
            "upid": 2,
            "code": "20010",
            "level": "B"
        }, {
            "id": 14,
            "name": "篮球",
            "upid": 2,
            "code": "20012",
            "level": "B"
        }, {
            "id": 15,
            "name": "足球",
            "upid": 2,
            "code": "20011",
            "level": "B"
        }]
    }, 

现在想做成

[
  {
    "id":1,
    "text": "田径",
    "upid": 0,
    "code": "",
    "level": "",
    "children":[
      {
        "id": 10,
        "text": "排球",
        "upid": 2,
        "code": "20007",
        "level": "B"
      },
      {
        "id": 11,
        "text": "网球",
        "upid": 2,
        "code": "20008",
        "level": "B"
      }
    ]
  }
]

等于是把 name换成了text,child换成了children
而且只有2级。最好是用es6的方法 ~

回复
阅读 879
1 个回答

function a(arr){

arr.map(value =>{

value.text = value.name

delete value.name

if(value.child){

value.children = value.child

delete value.child

a(value.children)

}

})

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏