Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Records in Javascript Object

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.

like image 841
devdar Avatar asked Jan 13 '23 04:01

devdar


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

people.length; // 2

And you can grab specific people based on their index:

people[0].name; // John
like image 171
Sampson Avatar answered Jan 24 '23 04:01

Sampson


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);
like image 21
Nuwan Dammika Avatar answered Jan 24 '23 04:01

Nuwan Dammika