4

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.

dcaswell
  • 3,137
  • 2
  • 26
  • 25
devdar
  • 5,564
  • 28
  • 100
  • 153
  • What do you mean by number of records in the object? – PSL Oct 09 '13 at 03:55
  • 1
    Your object doesn't contain two records, it contains three properties which you overwrite with the second set of values. Objects don't have a length (unless you add one yourself); what you need here is an array of objects, not a single object. – nnnnnn Oct 09 '13 at 03:56
  • See here for more information: http://stackoverflow.com/a/1345992/1861269 – zombiehugs Oct 09 '13 at 03:56
  • the object is a multidimensional array i would like to ge a count of the data in the object where john and smith are two elements in the object – devdar Oct 09 '13 at 03:57
  • 1
    Do you mean to say that you have a multi dimensional array of objects of type person? – PSL Oct 09 '13 at 03:58
  • 1
    The object as shown in the question is not an array, multidimensional or otherwise. If you have another variable that is an array please add details of that to your question. – nnnnnn Oct 09 '13 at 04:00
  • i think i confused the use of an array and an object i would like to hold several rows of data so for this i may need to use an array – devdar Oct 09 '13 at 04:01
  • Just for info, you can count the number of enumerable own properties of the object using [`Object.keys(obj).length`](http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.14). – RobG Oct 09 '13 at 04:02
  • Please change the question title.... – PSL Oct 09 '13 at 04:02

2 Answers2

8

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
Sampson
  • 265,109
  • 74
  • 539
  • 565
1

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);
Nuwan Dammika
  • 587
  • 9
  • 20