2017-03-14 4 views
0

전체 UL을 변환해야하며 자식 요소를 JSON 객체로 변환해야합니다.UL을 JSON 객체로 변환

function getData(el) { 
    el.find('li').each(function() { 
     data.push({ "nome": $(this).find('span').html(), "cargo": $(this).find('strong').html() }); 
    }); 
} 

JS 바이올린 :

이것은 우리가 무슨 짓을 https://jsfiddle.net/cbzo0ef2/2/

그러나 모든 요소는 동일한 수준에 있습니다. 이 경우 모든 수준을 유지해야합니다. 당신을 위해

+0

(function($) { function getData(el) { var curr = []; el.children('li, ul').each(function(i, child) { curr.push({ nodeName: child.nodeName, nome: $(child).find("> span").text(), cargo: $(child).find("> strong").text(), subLevel: getData($(child)) }); }); return curr } var result = getData($('.root')); console.log(JSON.stringify(result)); })(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="root"> <li><span>a</span><strong>b</strong></li><li><span>c</span><strong>d</strong></li><li><span>e</span><strong>f</strong></li><li> <ul> <li><span>g</span><strong>h</strong></li><li><span>i</span><strong>j</strong></li><li> <ul> <li><span>k</span><strong>l</strong></li></ul> </li></ul> </li></ul>
당신은 당신이 출력이? 당신이 객체를 원하는 경우에, 당신은 왜 사용하는 –

+0

"모든 수준이 유지 될 필요"가 무슨 뜻인지 점점 안하려는 JSON 형식을 지정할 수 있습니다 배열? – jmargolisvt

답변

0

$(this).parents("ul").length 것 트릭 :

function getData(el) { 
    el.find('li').each(function() { 
     data.push({ "nome": $(this).find('span').html(), "cargo": $(this).find('strong').html(), "dept": $(this).parents("ul").length }) 
    }); 
    } 

당신은

fiddle

0

이 솔루션은 당신의 HTML의 수준을 유지합니다 참조하여 JSON 구조에 부서를 렌더링하기 위해 추가 작업이 필요합니다

(function($) { 

    function getData(el) { 
     var data = []; 

     el.children('li').each(function() { 
      var currentElement = $(this); 

      var nomeElement = currentElement.children('span')[0]; 
      var cargoElement = currentElement.children('strong')[0]; 

      var item = {}; 

      if (nomeElement && cargoElement) { 
       item.nome = $(nomeElement).html(); 
       item.cargo = $(cargoElement).html(); 
      } 

      data.push(item); 

      var child = currentElement.children('ul')[0]; 

      if (child != null) { 
       item.children = getData($(child)); 
      } 
     }); 

     return data; 
    } 

    var data = getData($('.root')); 
    console.log(data); 

})(jQuery); 

fiddle : https://jsfiddle.net/52t58551/

0

jQuery Children을 사용하고 일부 재귀를 사용하면 모든 노드를 가져올 수 있습니다.

관련 문제