我有一个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绑定,并将所有与选定选区相关的候选人名称放在工具提示中。
目前的观点:
我的目的:
答案 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