I am trying to dynamically change the value of property by which the JSON object has to be grouped by . for example if my search criteria is location i want to display work location of employee as key and no of employees in that location as pair whereas the location is one of the property in JSON .
This is what i have done so far. i am able to group employees based on location and its count as key value pair.
var rows = [
{
"empId": 1,
"empName": "aaa",
"skillSet": "JAVA",
"location": "chennai"
},
{
"empId": 2,
"empName": "bbb",
"skillSet": "Angular",
"location": "chennai"
},
{
"empId": 3,
"empName": "ccc",
"skillSet": "Angular",
"location": "chennai"
},
{
"empId": 4,
"empName": "ddd",
"skillSet": "JAVA",
"location": "bangalore"
},
{
"empId": 5,
"empName": "eee",
"skillSet": "JAVA",
"location": "chennai"
},
{
"empId": 6,
"empName": "fff",
"skillSet": "JAVA",
"location": "bangalore"
},
{
"empId": 7,
"empName": "ggg",
"skillSet": "oracle",
"location": "chennai"
},
{
"empId": 8,
"empName": "hhh",
"skillSet": "JAVA",
"location": "hyderabad"
},
{
"empId": 9,
"empName": "iii",
"skillSet": "JAVA",
"location": "hyderabad"
}
]
var occurences = rows.reduce(function (r, row) {
r[row.location] = ++r[row.location] || 1;
return r;
}, {});
var result = Object.keys(occurences).map(function (key) {
return { key: key, value: occurences[key] };
});
console.log(result);
and my result is
[{
"key": "chennai",
"value": 5
},
{
"key": "bangalore",
"value": 2
},
{
"key": "hyderabad",
"value": 2
}
]
As yo can see i have hardcoded the location directly
r[row.location] = ++r[row.location] || 1;
instead i want to make to dynamically like i can also should be able to group it using other attributes like skillSet also . But How do it .