How can I recursively create a UL/LI's from JSON data - multiple layers deep

前端 未结 7 751
暖寄归人
暖寄归人 2020-12-30 12:32

I am trying to use use the following JSON data to create the following similar structure in a recursive inner function with not much luck, really need some help and so if an

相关标签:
7条回答
  • 2020-12-30 13:24

    Pure ES6

    var foo=(arg)=>
    `<ul>
    ${arg.map(elem=>
        elem.sub?
            `<li>${foo(elem.sub)}</li>`
            :`<li>${elem.name}</li>`
        )}
    </ul>`
    

    JSON example

       var bar = [
      {
        name: 'Home'
      }, {
        name: 'About'
      }, {
        name: 'Portfolio'
      }, {
        name: 'Blog'
      }, {
        name: 'Contacts'
      }, {
        name: 'Features',
        sub: [
          {
            name: 'Multipage'
          }, {
            name: 'Options',
            sub: [
              {
                name: 'General'
              }, {
                name: 'Sidebars'
              }, {
                name: 'Fonts'
              }, {
                name: 'Socials'
              }
            ]
          }, {
            name: 'Page'
          }, {
            name: 'FAQ'
          }
        ]
      }
    ]
    var result=foo(bar)
    

    Your 'result' will be valid HTML

    0 讨论(0)
提交回复
热议问题