Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

javascript 数组json 转化为json格式

如题,求个优雅的递归写法把图一数组json 转化成图二json格式(ps: 数组json中的age的值,是转化后json中的key

图一:数组json

[
  {
   "age": 'test',
   "height": 180,
    children[
      {
         "age": 'test2',
         "height": 181,
          children[
            {
             "age": 'test3',
             "height": 178,
            }
          ] 
      },
      {
         "age": 'test4',
         "height": 170,
      }
   ] 
  },
  {
     age": 'test5',
    "height": 175,
  }
]

图二:json格式

{
  test: {
    test2: {
      test3: ''
    },
    test4: ''
  },
  test5: ''
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

image.png

function deep(list){
    return list.reduce((s,n)=>{
        s[n.age] = deep(n.children || [])
        return s
    }, {})
}
deep(list)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...