如何匹配svg元素id与json键

时间:2015-11-20 09:57:50

标签: javascript jquery json d3.js svg

我有一个svg (can be viewed here),我想在其中提供一些关于点击的数据。数据采用json格式,我希望将svg元素的每个id与json data中的键匹配,如果两者都相同则执行某些操作。例如,如果Json键是关键:中国和元素id是中国然后从json呈现中国的信息。我已经提取了所需的数据格式,我无法弄清楚如何将这些键与元素ID匹配。

这就是我访问数据集的方式

 var countriesByName = d3.nest()
            .key(function (d) {
            return d.Country_Names;
        })


             .entries(data);
        // creating dropdown
        var data = JSON.stringify(countriesByName)
        var data = JSON.parse(data);

//this is the key I would like to match with element ids:

    var keys = function( d ) {
                return d.key;
            }

从此,json的格式变为

    [{"key":"Albania",
   "values":  [{"Continent":"Europe",
               "Country_Names":"Albania",
                "Total":"3.8",
                 "Change_total":"-38.7",
               "Main activity electricity and heat production":"0.1",
                "Main activity electricity plants":"",
                "Main activity CHP plants":"","Unallocated autoproducers / Other energy industry own use":"0.1",
            "Other":"1.4",
            "Manufacturing industries and construction":"1",
             "Iron and steel":"0",
          "Chemical and petrochemical":"0",
           "Machinery":"",
          "Mining and quarrying":"",
          "Food and tobacco":"0.1",
         "Paper, pulp and printing":"",
         "Construction":"0",
         "Transport":"2.2",
         "Road":"2.2",
          "Domestic aviation":"",
          "Rail":"0",
         "Domestic navigation":"0.1",
           "Residential":"0.2",
          "Commercial and public services":"0",
         "Agriculture/forestry":"0.2",
          "Sub-bituminous coal / Lignite":"",
          "Other bituminous coal":"",
          "Natural gas":"0",
         "Motor gasoline excl. bio":"0.3",
         "Gas/diesel oil excl. bio":"2.2"}]} 

小提琴:https://jsfiddle.net/n5v84svm/47/

1 个答案:

答案 0 :(得分:1)

您可以从远程URL获取JSON数据,然后可以使用任何键值进行过滤,以将特定数据对象从数据源中获取。请检查以下代码。如果我的解决方案对您的问题有误,请道歉。

//Get Data from the Remote URL
    var countryData=$.get("https://gist.githubusercontent.com/heenaI/cbbc5c5f49994f174376/raw/c3f7ea250a2039c9edca0b12a530f108d6304e1c/data.json");  
countryData=JSON.parse(countryData.responseText);
//this is the key I would like to match with element ids:
var keys = function( d ) {
    var keyData=data.filter(function(value) {   return value.Country_Names == d;});
    return keyData;     
        }