Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

javascript - Count iterations of an object inside an array

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: "[email protected]", Name: "Bob Smith", ?Number: "555-555-1234", Size: "2"}
    
    1: { Email: "[email protected]",  Name: "Jenny Girl", ?Number: "222-333-1234",  Size: "4"}
    
    2: {  Email: "[email protected]",   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.

question from:https://stackoverflow.com/questions/65865370/count-iterations-of-an-object-inside-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...