2

我需要计算 json 数组中重复项目的数量,并将重复项目显示为单个项目,并且计数应该显示它重复了多少个 tiems..

请检查以下代码和输出,以便您理解:

[{
    "Name": "Jacob",
    "Gender": "Male",
    "City": "Newyork",
    "State": "Newyork"
}, {
    "Name": "Mason",
    "Gender": "Male",
    "City": "Los Angeles",
    "State": "California"
}, {
    "Name": "Ethan",
    "Gender": "Male",
    "City": "Chicago",
    "State": "Illinois"
}, {
    "Name": "Noah",
    "Gender": "Male",
    "City": "Newyork",
    "State": "NewYork"
}, {
    "Name": "Sophia",
    "Gender": "Female",
    "City": "Los Angeles",
    "State": "California"
}, {
    "Name": "Emma",
    "Gender": "Female",
    "City": "Los Angeles",
    "State": "California"
}, {
    "Name": "Isabella",
    "Gender": "Female",
    "City": "Chicago",
    "State": "Illinois"
}, {
    "Name": "Olivia",
    "Gender": "Female",
    "City": "Chicago",
    "State": "Illinois"
}, {
    "Name": "Elizabeth",
    "Gender": "Female",
    "City": "Newyork",
    "State": "Newyork"
}, {
    "Name": "zoey",
    "Gender": "Female",
    "City": "Newyork",
    "State": "Newyork"
}]

json的期望输出是

Newyork : 4Times,

芝加哥:3次,

请找到小提琴:

http://jsfiddle.net/vamsikrishna981/dMrNv/
4

1 回答 1

2

试试这个http://jsfiddle.net/RHYFC/

请参阅小提琴上的 LONG VERSION 和 SHORT VERSION

Javascript

var result = {};
for(var i = 0; i < data.length; i++){
    for(var item in data[i]){
        if(!result[item]){
            result[item] = {};
        }

        if(!result[item][data[i][item]]){
            result[item][data[i][item]] = 0;
        }

        result[item][data[i][item]]++;
    }
}
于 2013-09-01T17:01:51.607 回答