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.

9
  • What do you mean by number of records in the object? Commented Oct 9, 2013 at 3: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. Commented Oct 9, 2013 at 3:56
  • See here for more information: stackoverflow.com/a/1345992/1861269 Commented Oct 9, 2013 at 3:56
  • 1
    Do you mean to say that you have a multi dimensional array of objects of type person? Commented Oct 9, 2013 at 3: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. Commented Oct 9, 2013 at 4:00

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

if i have to add data to this array will it be like people.push('Smith',20.'M'); ?
@dev_darin Push a new object literal: people.push({ name: "Jane", age: 20, gender: "F" });.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.