I have a javascript object and I would like to count the number of records in that object. I have tried length and size however I am not getting a count.
Object
var person = new Object();
person.name = null;
person.age = null;
person.gender = null;
I then populate this Object with data like;
person.name = 'John';
person.age = 20;
person.gender = 'M';
person.name = 'Smith';
person.age = 22;
person.gender = 'M';
I would like to return a count with two rows of data.
What you want is an array of objects:
var people = [
{ name: "John", age: 20, gender: "M" },
{ name: "Smith", age: 22, gender: "M" }
];
From this you can get the length off the array:
people.length; // 2
And you can grab specific people based on their index:
people[0].name; // John
You are simply changing the same object. So the count will always be 1. If you want to get number of objects define a array and assign each object to that. Then you can get the count.
var perarray= new Array();
var person = new Object();
person.name = null;
person.age = null;
person.gender = null;
person.name = 'John';
person.age = 20;
person.gender = 'M';
perarray[0]=person;
person.name = 'Smith';
person.age = 22;
person.gender = 'M';
perarray[1]=person;
alert(perarray.length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With