如何将多个JSON对象合并为一个,并将两个值放在工具提示中

时间:2016-09-01 13:09:39

标签: javascript d3.js

我有一个JSON文件,其结构如下面的代码所示:

{
    "results": [
      {

        "name": "First Candidate",
        "result": 52,
        "victory": "winner",
        "region": "First region",
        "constituencyName": "First constituency",
        "constituencyNumber": 1,
        "partyName": "Ruling party",
        "partyShort": "PR",
        "partyStatus": "Right"
      },
      {
        "name": "Second Candidate",
        "result": 48,
        "victory": "looser",
        "region": "First region",
        "constituencyName": "First constituency",
        "constituencyNumber": 1,
        "partyName": "Opposition party",
        "partyShort": "OP",
        "partyStatus": "Left"
      }
   ]
}

现在所有对象都有单独的DIV。我试图将对象与制服" constituencyName"合并。在一个方面,将此选择与一个DIV绑定,并将所有与选定选区相关的候选人名称放在工具提示中。

目前的观点:

enter image description here

我的目的:

enter image description here

这是我的小提琴:http://jsfiddle.net/anton9ov/nwt2n04y/

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

var input = {
"results": [
  {

    "name": "First Candidate",
    "result": 52,
    "victory": "winner",
    "region": "First region",
    "constituencyName": "First constituency",
    "constituencyNumber": 1,
    "partyName": "Ruling party",
    "partyShort": "PR",
    "partyStatus": "Right"
  },
  {
    "name": "Second Candidate",
    "result": 48,
    "victory": "looser",
    "region": "First region",
    "constituencyName": "First constituency",
    "constituencyNumber": 1,
    "partyName": "Opposition party",
    "partyShort": "OP",
    "partyStatus": "Left"
  }
  ]};

var constituencyMap =
input.results.reduce(function(p, c){
      p[c.constituencyName] = p[c.constituencyName] || []

      p[c.constituencyName].push(c);

      return p;          
  }, {});

var result = Object.keys(constituencyMap).map(function(key){
                    return {constituencyName:key, value:constituencyMap[key]};
              });
// the result will be an array to retrieve the name
// result[index].constituencyName will have constituencyName
// and result[index].value will have value