Count iterations of an object inside an array

Viewed 54

I have a variable returning an array from the DB. Inside that array I need to count the instances of a specific object iteration.

I tried using jQuery.each and logging the output to check but was just getting individual results in the console. I was not getting the desired count. In the sample below I would expect to see: size 2 - count 1 size 4 - count 2

Sample Output

   0: {Email: "example@mai.com", Name: "Bob Smith", ​Number: "555-555-1234", Size: "2"}
    
    1: { Email: "example2@mai.com",  Name: "Jenny Girl", ​Number: "222-333-1234",  Size: "4"}
    
    2: {  Email: "example3@mai.com",   Name: "Johnny on the spot",  ​Number: "111-777-1234",  Size: "4"}

Using jquery what is the best way to achieve this? Is using something like .size?

My code I have attempted:

​​function xyz() {
jQuery.ajax({
data: {action: 'my_action'},
type: 'post',
url: my_ajax.ajax_url,
dataType: 'JSON',
success: function(data) {
jQuery.each(data, function(key,val){
var n = Object.keys(val.Size).size;
console.log(n);
        });

​​ ​​This gives me an 'undefined' console log readout.

2 Answers

You could store the value of Size as the property of an Object and count:

// Just for demo - that's your data response:
const data = [{Size: "2"}, {Size: "4"}, {Size: "4"}, {Size: "99"}]; 

const sizes = data.reduce((ob, item) => {
  if (!ob.hasOwnProperty(item.Size)) ob[item.Size] = 0;
  ++ob[item.Size];
  return ob;
}, {});

console.log(sizes);

var data = [
  {Email: "example@mai.com", Name: "Bob Smith", Number: "555-555-1234", Size: "2"},
  {Email: "example2@mai.com", Name: "Jenny Girl", Number: "222-333-1234",  Size: "4"},
  {Email: "example3@mai.com", Name: "Johnny on the spot", Number: "111-777-1234",  Size: "4"}
];

const sizes = data
    // collect each "Size" value from the data
    .map(e => e.Size)
    // use an object to count each instance
    .reduce((a, n) => ({...a, [n]: (a[n] || 0) + 1 }), {})

// log each object entry to the console
Object.entries(sizes)
    .forEach(([size, count]) => console.log(`size: ${size} count: ${count}`));

Related