javascript - 如何将 svg 元素 ID 与 json 键匹配

标签 javascript jquery json d3.js svg

我有一个 svg (can be viewed here)我想向其展示一些点击数据。数据为 json 格式,我想将 svg 元素的每个 id 与 json data 中的键匹配如果这两者都相同,那么就做点什么。例如,如果 Json key 是 key: china 并且元素 id 是 china 则从 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"}]} 

fiddle :https://jsfiddle.net/n5v84svm/47/

最佳答案

您可以从远程 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;     
        }

关于javascript - 如何将 svg 元素 ID 与 json 键匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33823761/

相关文章:

javascript - 检查所有数组项是否未定义或空字符串

javascript - PHP - Curl(存储在 session 中的处理程序)+使用此处理程序的 ajax 请求

jquery - 侧边栏 Accordion 状态和图标状态

c# - 如何将 JToken 转换为嵌套的 float 列表?

c# - JsonSchemaGenerator 未将字段设置为 required = false

javascript - Blade laravel 中的总值之和

javascript - 从内联javascript获取e参数

javascript - 在 Javascript/jQuery 中包装一个函数

javascript - 如何避免这个很长的 if else 语句

python - 如何在python中将json转换为树