Reputation: 665
I am trying to create a bar chart for the roles by their count using dc.js and crossfilter. Need to deal with nested JSON.
Sample data set
[ { "user":"Mani"
"age":55,
"area":"NORTH",
"role": [
{
"roleId": 15,
"role": "Operator",
"at": "2018-10-30T07:53:10.433Z",
"createdAt": "2018-10-30T07:53:10.449Z"
},
{
"statusId": 16,
"status": "Supervisor",
"at": "2018-10-30T07:53:18.359Z",
"createdAt": "2018-10-30T07:53:18.359Z"
},
{
"statusId": 26,
"status": "Manager",
"at": "2018-10-30T13:01:50.296Z",
"createdAt": "2018-10-30T13:01:50.296Z"
}
]
}, {
"user":"Kandan"
"age":65,
"area":"SOUTH",
"role": [
{
"roleId": 15,
"role": "Operator",
"at": "2018-10-30T07:53:10.433Z",
"createdAt": "2018-10-30T07:53:10.449Z"
},
{
"statusId": 16,
"status": "Supervisor",
"at": "2018-10-30T07:53:18.359Z",
"createdAt": "2018-10-30T07:53:18.359Z"
}
]
}
]
I tried creating a chart by using values from the root level of each user but when I tried accessing the role
key I am somehow able to use only one role not all the roles on other hand it returns the array to the dimension. The basic idea is to have role.role under x-axis and their count on the y-axis. How do I achieve this?
Sample output
Upvotes: 2
Views: 417
Reputation: 20120
Your problem isn't really the nested JSON; it's the fact that you have multiple roles for each user.
To fetch the roles for each user, you can use an accessor which returns an array of role names:
var roleDimension = cf.dimension(d => d.role.map(r => r.role), true);
The second parameter specifies that you want a "tag" or "array" dimension. This is a special mode where each row will be counted multiple times, once for each tag in the array which the dimension key accessor returns.
I see you want to use this for a bar chart, which is good - don't use this for any chart which implicitly adds up to 100%! Since the categories are not mutually exclusive, the behavior can be confusing even when you are careful not to imply 100%.
Upvotes: 2