Count Records in a Javascript Object

I have a javascript object , and I would like to count the number of records in this object. I tried length and size, but I do not get the bill.

An object

 var person = new Object();
    person.name = null;
    person.age = null;
    person.gender = null;

Then I populate this object with the following data:

person.name = 'John';
person.age = 20;
person.gender = 'M';

person.name = 'Smith';
person.age = 22;
person.gender = 'M';

I would like to return a counter with two rows of data.

+4
source share
2 answers

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 from the array:

people.length; // 2

And you can capture specific people based on their index:

people[0].name; // John
+8
source

. , 1. , . .

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

All Articles