0

I suppose the answer Access / process (nested) objects, arrays or JSON is different from what I want to achieve. The above link questions about accessing object in from a nested array set.

I have an array of objects like below

[
 {
   "type": "type 1",
   "status": "success"
 },
 {
   "type": "type 2",
   "status": "success"
 },
 {
   "type": "type 1",
   "status": "error"
 },
 {
   "type": "type 1",
   "status": "success"
 }
]

What I intend to get is something like this

 2 type 1 has an event success
 1 type 1 has an event error
 1 type 2 has an event success

Basically, I want the count of type whose status is success and error.

underscore.js might be useful here, but I could not make that happen. Help would be appreciated Thanks

Community
  • 1
  • 1
  • Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Teemu Jan 18 '17 at 13:09
  • The accepted answer in the linked dup candidate can very well be applied to your task. If you need a copy-pasta answer, then it's not suitable ... – Teemu Jan 18 '17 at 13:15

1 Answers1

0

try following, you can use _.countBy

var arr = [
 {
   "type": "type 1",
   "status": "success"
 },
 {
   "type": "type 2",
   "status": "success"
 },
 {
   "type": "type 1",
   "status": "error"
 },
 {
   "type": "type 1",
   "status": "success"
 }
];

var res = _.countBy(arr,function(obj){
return obj.type + " has an event " + obj.status
});

for(var item in res)
{
   console.log(res[item] + " " + item);
}
K D
  • 5,889
  • 1
  • 23
  • 35