2017-03-16 2 views
0

JSON 배열에서 모든 범주 제목을 가져 오려고합니다. 그러나 모든 객체가 범주를 갖는 것은 아닙니다. 이 때문에 데이터를 추가하려고하면 계속 정의되지 않고 나머지 데이터는 추가되지 않습니다.빈 개체가있는 Json Array를 반복합니다.

Json 파일에 아무 것도없는 경우 카테고리를 기본 카테고리로 지정하고 싶습니다. 또는 태그의 제목을 카테고리로 지정하십시오.

몇 가지 방법을 시도했지만 아무 것도 작동하지 않는 것 같습니다. 지금까지 JSON 파일에 대한 다운로드 링크와 함께 수행 한 내용을 아래에서 보았습니다. ProblemArea 코멘트를 사용하여 내가 시도한 것을 보여줍니다.

도움이 될 것입니다.

CODE - 당신은 정말 신속하고 더러운 검사를 원한다면, 그냥이 있거나 체크 그래서 제목이 경우 기본 값을 설정할 수 있습니다

$("#search-btn").click(function (e) { 
 
    
 
      var userText = $.trim($('#searchArea').val()); 
 
      $('.full-post-img').css('display', 'none'); 
 
      $('.overlay-hugeinc').css('left', '-9999px'); 
 
    
 
      $.getJSON('http://www.capetownetc.com/api/get_search_results/?search=' + userText, { 
 
        srsearch: userText 
 
        , action: "query" 
 
        , list: "search" 
 
        , format: "json", 
 
       }, 
 
         
 
       function (data) { 
 

 
        $("#searchR").empty().append('<p class="results">RESULTS</p>'); 
 
       
 
        if(userText.length === 0){ 
 
         $("#searchR").empty().append("<p class='results'>Please enter a keyword</p>"); 
 
         $('#sLoad').css('opacity', '0'); 
 
        } 
 
        else{ 
 
         $("#swipe").empty(); 
 
         
 
         $.each(data.posts, function (i, item) { 
 
//       $('#sLoad').css('opacity', '0'); 
 
          
 
          //EXCERPT 
 
          var ex = item.excerpt; 
 
          var maxLength = 100; 
 
          ex = ex.substr(0, maxLength); 
 
          
 
          //THUMBNAIL 
 
          var imgThumb1 = item.thumbnail_images.full.url; 
 
          
 
          //****PROBLEM AREA**** 
 
          //CATEGORY 
 
          var cat = item.categories[0].title; 
 
          
 
          if(cat.hasOwnProperty(i)){ 
 
           console.log('Is valid'); 
 
          } 
 

 
          
 
          console.log(cat); 
 
          
 
          $("#swipe").append('<div class="p1 full-post-text"><a class="p1 link-click" id="post2" target="_blank"></a><div class="p1 text-post-img"><span class="p1 card-img1" id="p1Img" style="background-image:url(' + imgThumb1 + ');"></span><a class="p1 post-cat">' + cat + '</a> </div><div class="p1 full-text-info"><h2 class="p1 text-heading" id="p1Heading">' + item.title + '</h2><p class="p1 text-post-desc" id="p1Desc">' + ex + '</p><p class="p1 post-source" id="p1Source">/</p></div></div>'); 
 
          
 
        }); 
 
        } 
 
       
 
       }); 
 
});

JSON Data File

+0

json 구조 –

답변

0

정의되지 않았습니다.

var cat = item.categories[0].title || "default value" 

그리고 당신이 정말로 싶어 바다에 가면 : 당신은 간단한 경우-문이 청소 할 수

var cat = (item && item.categories && item.categories[0] && item.categories[0].title) || "default value" 

. 정의되지 않은 검사를 몇 가지 시도해보십시오.

+0

을 다시 만들려면 'yourArray.map()'을 사용할 수 있습니다. 두 번째 경로를 내려가려면 item.categories.length를 확인하거나 다음 조건에서 예외를 throw해야합니다. –

+0

아니요. https://jsfiddle.net/v1qg7vv4/ –

+0

하, 네 말이 맞아. 왜 내가 그렇게 생각하는지 모르겠다. 다른 언어로 된 것일 수도 ... –