2017-04-30 2 views
0

간단한 "플러그 앤 플레이"맵 템플리트를 만들려고합니다. 사용자가 지오이드 및 값이있는 CSV 파일을 넣은 다음 값을 choropleth로 볼 수 있습니다.D3/JS에서 두 개의 데이터 세트 병합

다른 옵션이있는 경우 지금은 두 개의 데이터 세트 (지도 및 값) 더블 루프를 사용하여 병합하지만 궁금 :

이 코드 덩어리가 지리 (fresh_ctss를)로드하는 함수 내에서 유지

:

d3.csv("data/communities_pop.csv", function(error, comms) 
      { 
       csv = comms.map(function(d) 
       { 
        //each d is one line of the csv file represented as a json object 
        // console.log("Label: " + d.CTLabel) 
        return {"community": d.community, "population" :d.population,"label": d.tract} ; 
       }) 

       csv.forEach(function(d, i) { 
       fresh_ctss.forEach(function(e, j) { 
       if (d.label === e.properties.geoid) { 
        e.properties.community = parseInt(d.community) 
        e.properties.population = parseInt(d.population) 
        } 
       }) 
       }) 

답변

2

분명히 두 개의 루프 (또는 중첩 루프)가 필요합니다. 가장 최적의 방법은 반복이 얼마나 필요한지를 제한하는 것입니다. 현재 첫 번째 루프는 모든 csv 행을 통과합니다. 다음 중첩 루프는 모든 csv 행 (새로운 다른 객체)을 통과 한 다음 csv에 행이있는 횟수만큼 fresh_ctss의 모든 항목을 통과합니다.

배열 대신 객체에 행을 매핑 한 경우 행을 한 번 (총) 반복 한 다음 fresh_ctss (다시 한 번)의 요소를 한 번 반복 할 수 있습니다. 아래 코드는 commstract 중복이 없다고 가정합니다.

all_comms = {} 
comms.forEach(function(d) { 
    all_comms[d.tract] = {"community": d.community, "population": d.population} 
}) 
fresh_ctss.forEach(function(e) { 
    comm = all_comms[e.properties.geoid] 
    e.properties.community = parseInt(comm.community) 
    e.properties.population = parseInt(comm.population) 
} 
관련 문제