2016-09-08 4 views
0

URL에 ID-1 또는 URL이있는 경우 JSON 파일에서 세 가지 "집"과 "노출"을 모두 가져 와서 저장해야하는 문제가 발생했습니다. ID-2 등. 나는 URL에서 전달 된 올바른 매개 변수에 대해 .JSON Listening을 통해 반복되는 반복문을 사용합니다. 예를 들면. http://localhost/?houseblock=ID-1은 이제 ID-1 안에 JSON 만로드합니다. 하지만 나중에 집과 노출 수를 모두 가져와 저장해야합니다..getJson 여러 개 .each 루프에서 여러 객체 저장

저는이 작업을 올바르게 수행하는 방법에 대해 약간 익숙하지가 않습니다. "집"과 "노출"을 잡아서 하나의 루프를 마친 다음 두 번째 루프에서 두 번째 루프를 다시 잡으라고 말했습니다. 집 "과"노출 ". 하지만 그럴 것 같지 않습니다.

JSON jsonFile.json

{ 
    "ID-1":{ 
     "1-1":{ 
     "house":6, 
     "exposure":1 
     }, 
     "1-2":{ 
     "house":1, 
     "exposure":3 
     }, 
     "1-3":{ 
     "house":3, 
     "exposure":2 
     } 
    }, 
    "ID-2":{ 
     "2-1":{ 
     "house":3, 
     "exposure":2 
     }, 
     "2-2":{ 
     "house":6, 
     "exposure":5 
     }, 
     "2-3":{ 
     "house":1, 
     "exposure":1 
     } 
    } 
} 

JQUERY이 당신이 찾고 있지만하는지 경우

$(document).ready(function() 
{ 
    // -- Listen to URL Changes --// 
    var urlListen; 
    (window.onpopstate = function() 
    { 
     var match, 
      pl = /\+/g, // Regex for replacing addition symbol with a space 
      search = /([^&=]+)=?([^&]*)/g, 
      decode = function(s) 
      { 
       return decodeURIComponent(s.replace(pl, "-")); 
      }, 
      query = window.location.search.substring(1); 
     urlListen = {}; 
     while (match = search.exec(query)) urlListen[decode(match[1])] = decode(match[2]); 
    })(); 
    var retrieveAll = $.getJSON('jsonFile.json', function(data) {}).done(function(data) 
    { 
     $(data[urlListen["houseblock"]]).each(function(i, val) 
     { 
      $.each(val, function(j, b) 
      { 
       $.each(b, function(k, v) 
       { 
        console.log(k + " : " + v); 
        if (k == "house") 
        { 
         houseObj = v; 
         houseObj2 = v; 
         houseObj3 = v; 
        } 
       }); 
      }); 
     }); 
    }).fail(function(data) 
    { 
     console.log("error"); 
    }).always(function(data) 
    { 
     console.log("complete"); 
    }); 
    retrieveAll.complete(function(data) 
    { 
     init(); 
    }); 
}); 

function init() 
{ 
    console.log(houseObj); 
    console.log(houseObj2); 
    console.log(houseObj3); 
} 

답변

1

완전히 확실하지 다음 코드를 저장 모든 houseexposure 값을 자신의 배열에 저장합니다. $.each을 사용할 필요는 없습니다. Javascript의 기본 인 map을 사용하는 것이 더 간단합니다.

게시 한 코드에서 로직의 구성 요소를 추상화하여 getCurrentHouseBlockID (또는 이와 비슷한) 함수로 추상화 할 수 있다고 가정합니다.

var id = getCurrentHouseBlockID(); // 'ID-1' 
var dataForID = Object.keys(jsonData[id]); // ['1-1', '1-2', '1-3'] 
var houseNums = dataForID.map(function getHouseNum(key) { 
    return dataForID[key].house; 
}); 
var exposureNums = dataForID.map(function getExposureNum(key) { 
    return dataForID[key].exposure; 
});