search

Home  >  Q&A  >  body text

javascript - ES5/6 merging arrays and objects

[{a1:1},{a2:2},{a3:3}]
// 上面结构转成下面结构~!求教思路。
[{
  a1:1,
  level:[
    {
      a2:2,
      level:[
        {
          a3:3
        }
      ]
    }
  ]
}]
大家讲道理大家讲道理2770 days ago516

reply all(3)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:48:47

    [{a1:1},{a2:2},{a3:3}]
    .reverse()
    .reduce((a,b) => {
        return b.level = [ a ],b
    })

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:48:47

    var arr = [{a1:1},{a2:2},{a3:3}] 
    
    arr.reduce(function(pre,cur){
        pre.level = [cur]
        return pre.level[0]
    })
    
    var result = [arr[0]]
    
    console.log(JSON.stringify(result))

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:48:47

    JSON.stringify([{a1:1},{a2:2},{a3:3}].reduce((a,b)=>{
        let c = a
        while(c.level){
            c = c.level[0]
        }
        c.level = [b]
        return a
    }))

    reply
    0
  • Cancelreply