0

Consider this code that is accessing the data of a javascript object.

animalData.animal[i].type

'animal' : [ 
  {'type':'dog', 'colour':'brown'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'orange'},
  {'type':'frog', 'colour':'green'},
  {'type':'cat', 'colour':'pink'},
  {'type':'dog', 'colour':'yellow'},
  {'type':'cat', 'colour':'grey'},
  {'type':'chicken', 'colour':'black'},
  {'type':'dog', 'colour':'yellow'}
]

Using modern JS how can I transform the above into another array of objects that looks like this. eg. shows a count of each and removes the duplicates?

[
  {'type':'dog', 'count':'4'},
  {'type':'cat', 'count':'3'},
  {'type':'chicken', 'count':'2'},
  {'type':'frog', 'count':'1'},
]
Timmy Lee
  • 785
  • 1
  • 11
  • 25

1 Answers1

1

You can reduce it and take Object values:

var data=[ {'type':'dog', 'colour':'brown'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'orange'}, {'type':'frog', 'colour':'green'}, {'type':'cat', 'colour':'pink'}, {'type':'dog', 'colour':'yellow'}, {'type':'cat', 'colour':'grey'}, {'type':'chicken', 'colour':'black'}, {'type':'dog', 'colour':'yellow'}];

var result = Object.values(data.reduce((acc, {type})=>{
  acc[type] = acc[type] || { type, count:0 };
  acc[type].count += 1;
  return acc;
},{}));

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19
  • thanks for the reply! but my data is part of a larger javascript object and i can't seem to the get the above to work.. animalData.animal[i] for example is where all the animal data is within the object – Timmy Lee Jun 01 '20 at 11:10
  • @TimmyLee, the answer is according to your expected output. How you want output to be? – gorak Jun 01 '20 at 11:19
  • my bad.. i positioned the code above below another transformation on that array.. so it was no longer an array but a string of values! it works! many thanks! – Timmy Lee Jun 01 '20 at 11:54