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

前端 未结 7 784
暖寄归人
暖寄归人 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:05

    I was searching for general parent child element function and I saw these answers, and I took some pieces of code from here and there and made this function. I decided to share my code as an answer, in case someone like me will find this post when he is searching for a general parent child html element draw function:

    function drawRecElements(arr, html, elements) {
        if (typeof (html) === 'undefined') {
            var html = '';
        }
        if (typeof (elements) === 'undefined') {
            var elements = {child: '
  • ', childClose: '
  • ', parent: '
      ', parentClose: '
    '}; } if (typeof (arr) === 'string') { return elements.child + arr + elements.childClose; } else if (typeof (arr) === 'object') { for (i in arr) { if (typeof (arr[i]) === 'string') { html += elements.parent + elements.child + i + elements.childClose + elements.child + arr[i] + elements.childClose + elements.parentClose; } else if(typeof (i) === 'string' && (isNaN(i))){ html += elements.parent + elements.child + i + elements.childClose + elements.child + drawRecElements(arr[i],'',elements) + elements.childClose + elements.parentClose; } else if (typeof (arr[i]) === 'object') { html = drawRecElements(arr[i], html,elements); } } } return html; }

    https://jsfiddle.net/kxn442z5/1/

提交回复
热议问题