12

How would I count how many objects there are inside an array?

The array looking like:

[ {id: 1}, {id: 2}, ...]

I assume I could use count() if it was PHP, but what about NodeJS/Javascript?

Edit:

asd

if (offer.items_to_receive.length > 0) { 
    console.log("items: " + offer.items_to_receive.length);
    for(var i = 0; i < offer.items_to_receive.length; i++) {
        usersInRound.push(offer.steamid_other);
    }
}

logData('Accepted trade offer from ' + offer.steamid_other + '. (tradeofferid: ' + offer.tradeofferid + ')\nWorth ' + offer.items_to_receive.length + ' tickets. ');

How come it can read the "worth X tickets", but not the other part?

Jon
  • 7,848
  • 1
  • 40
  • 41
prk
  • 3,781
  • 6
  • 17
  • 27
  • if your question was caused by your own typo (something you seem to indicate in a comment), then please delete your question. – jfriend00 Mar 17 '15 at 06:02
  • Well it seems it wasn't, two seconds, updating the post. – prk Mar 17 '15 at 06:04
  • Based on your edit, `offer.items_to_receive` is `undefined`. There is some problem earlier in your code that is making that property not be what you think it is. And, you certainly can't read the `.length` property of `undefined`. This should be basic debugging of your own code. – jfriend00 Mar 17 '15 at 06:07
  • Well how come it can read it at the end? (Check the \nWorth X tickets part) it can read the .length there? – prk Mar 17 '15 at 06:13
  • It can also read the .length of it at the "items" part. – prk Mar 17 '15 at 06:15
  • Based on your screen shot, it's throwing an exception before it gets to your `for` loop. This question is pretty screwed up. First, you've completely changed it. Second, you're not disclosing enough of the relevant code for anyone to have any idea what's going on. Third, now you're claiming lines of code after the exception are working fine which doesn't make any sense. – jfriend00 Mar 17 '15 at 06:18

3 Answers3

27

Use .length

var data = [{
    id: 1
}, {
    id: 2
}];

console.log(data.length);

Update, in your edit I see that

offer.items_to_receive is undefined, ensure that object offer has property items_to_receive (should be array);

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
10
list = //YOUR OBJECT DATA

count= Object.keys(list).length;

Object.keys() gives the count of keys

That should give proper count

Zuber Surya
  • 839
  • 7
  • 17
1

I think your question should be How to get Array Size in Javascript?

Answer: Use the length method.


Examples:

[1,2,3].length
// => 3

var a = { num: 1, obj: {}, arr: [{}, 3, "asd", {q: 3}, 1] }
a.arr.length
// => 5
Community
  • 1
  • 1
Sheharyar
  • 73,588
  • 21
  • 168
  • 215