sjw0525
sjw0525

Reputation: 329

Length of object is returning undefined

I have an object that I am trying to get the length of(see how many objects are inside). The code that creates the object is below:

 var threeDSCards = [];
 var card = {}

card[0] = {cardid: 10127, cardnumber: 411111111111, expMonth: 02, expYear: 18};                    
card[1] = {cardid: 10128, cardnumber: 411111111111, expMonth: 01, expYear: 19};

threeDSCards.push(card);

The code outputs this in console for the object:

[{
"0":{"cardid":10127,"cardnumber":411111111111,"expMonth":2,"expYear":18},
"1":{"cardid":10128,"cardnumber":411111111111,"expMonth":1,"expYear":19}
}]

I am expecting the length to be 2 since there are 2 cards stored in the object

Upvotes: 0

Views: 1615

Answers (2)

francium
francium

Reputation: 2480

You can use Object.keys(yourObject).length to get the number of keys (properties) an object has.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

If you are doing like above it will create a key value pair of objects, if you need just plain objects, you just need to create new variable and push them to the array

DEMO

 var threeDSCards = [];
 var card = {}

var card1 = {cardid: 10127, cardnumber: 411111111111, expMonth: 02, expYear: 18};                    
var card2 = {cardid: 10128, cardnumber: 411111111111, expMonth: 01, expYear: 19};

threeDSCards.push(card1);
threeDSCards.push(card2);
console.log(threeDSCards.length);

Upvotes: 2

Related Questions