187

Suppose I have the following object in JavaScript:

var object = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}; 

How do I find out how many values exist in the object?

8
  • 8
    Hold on! JS has no tuples and no dictionaries. That is called an object (written in literal notation), although it looks like a Python dictionary. What do you call a tuple in the above example though? Commented Aug 28, 2009 at 9:36
  • How do you suggest to rename this question? Commented Aug 28, 2009 at 9:44
  • Maybe "attributes" instead of "tuples"? That's assuming you want the answer to be 3 with the above 'object'. Commented Aug 28, 2009 at 9:50
  • 1
    Yeah. It is duplicated because I didn't know how to ask properly. We can close it as a duplicate. Commented Aug 28, 2009 at 14:24
  • 31
    It's simple, guys: Object.keys(myObject).length, see my post. Commented Nov 2, 2012 at 7:20

8 Answers 8

564

You can do that by using this simple code:

Object.keys(myObject).length
Sign up to request clarification or add additional context in comments.

12 Comments

@Andrew I wouldn't say "far from fully" I would say not supported in IE8 and below. Also, Polyfill.
If community can close questions, community should be able to change correct answer.
This should definitively be the correct answer, it's simple and elegant! @Iscariot +1: can't agree more!
This should be the accepted answer, I don't think the argument that "but it doesn't work in IE8" is any excuse. The only possible reason for trying to support it is if industry are still using windows XP. In which case, I think switching to an alternative browser is a better choice, continuing to develop and support IE8 is a long road thats going nowhere, you are going to have to re-work your code at some point if it only works in IE.
If you want to write your code to cater to tech backwaters, feel free. I hope you also optimize all your code for 2400 baud connections. Enjoy living in the past.
|
113

There's no easy answer, because Object — which every object in JavaScript derives from — includes many attributes automatically, and the exact set of attributes you get depends on the particular interpreter and what code has executed before yours. So, you somehow have to separate the ones you defined from those you got "for free."

Here's one way:

var foo = {"key1": "value1", "key2": "value2", "key3": "value3"};
Object.prototype.foobie = 'bletch'; // add property to foo that won't be counted

var count = 0;
for (var k in foo) {
    if (foo.hasOwnProperty(k)) {
       ++count;
    }
}
alert("Found " + count + " properties specific to foo");

The second line shows how other code can add properties to all Object derivatives. If you remove the hasOwnProperty() check inside the loop, the property count will go up to at least 4. On a page with other JavaScript besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

7 Comments

You shouldn't use an empty object to access Object.prototype. Just use Object.prototype.hasOwnProperty.call(foo, k).
why don't you just do foo.hasOwnProperty(k). Am I missing something? I mean even JavaScript type derives from Object.prototype, and it will have a hasOwnProperty() method.
@Elijah: I don't see what's wrong with the way I did it, but yes, your way should work, too.
@bucabay: The purpose of the test is to find those properties of 'foo' that aren't present on every other Object derivative. It might be enlightening to remove the test, and see how high count goes. You'll find it to be in the dozens. Just for one, you'll find a reference to "hasOwnProperty()" in both 'foo' and 'empty', because "member functions" are properties of objects, too, not just data as in some other languages.
@WarrenYoung The statement empty.hasOwnProperty(k) will always be FALSE since empty objects have no immediate properties. foo.hasOwnProperty(k) will return only immediate properties, not inherited properties from Object.prototype.
|
51

Use underscore library, very useful: _.keys(obj).length.

1 Comment

With underscore.js, you can use _.size(obj).
12

You can iterate over the object to get the keys or values:

function numKeys(obj)
{
    var count = 0;
    for(var prop in obj)
    {
        count++;
    }
    return count;
}

It looks like a "spelling mistake" but just want to point out that your example is invalid syntax, should be

var object = {"key1":"value1","key2":"value2","key3":"value3"};

Comments

11
 var miobj = [
  {"padreid":"0", "sw":"0", "dtip":"UNO", "datos":[]},
  {"padreid":"1", "sw":"0", "dtip":"DOS", "datos":[]}
 ];
 alert(miobj.length) //=== 2

but

 alert(miobj[0].length) //=== undefined

this function is very good

Object.prototype.count = function () {
    var count = 0;
    for(var prop in this) {
        if(this.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}

alert(miobj.count()) // === 2
alert(miobj[0].count()) // === 4

2 Comments

Extending native objects is a bad practice. Don't do it.
when i use this code then bootstrap dropdown is not working
5

This function makes use of Mozilla's __count__ property if it is available as it is faster than iterating over every property.

function countProperties(obj) {
  var count = "__count__",
  hasOwnProp = Object.prototype.hasOwnProperty;

  if (typeof obj[count] === "number" && !hasOwnProp.call(obj, count)) {
    return obj[count];
  }
  count = 0;
  for (var prop in obj) {
    if (hasOwnProp.call(obj, prop)) {
      count++;
    }
  }
  return count;
};

countProperties({
  "1": 2,
  "3": 4,
  "5": 6
}) === 3;

1 Comment

Note that this attribute was deprecated in Firefox 4 and removed shortly thereafter, so it hasn't been present in any browser for several years.
4

EDIT: this will case errors with jquery to happen, plus some other inconveniences. YOU SHOULD NOT USE IT: (perhaps if one could add a privaate method instead of a public property function, this would be OK, but don't have the time now). Community wikied

do not use:

Even though javascript's object by default doesn't have the count function, classes are easily extendable, and one can add it oneself:

Object.prototype.count = function () {
    var count = 0;
    for(var prop in this) {
        if(this.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}

So that after that one can execute

var object = {'key1': 'val1', 'key2':'val2', 'key3':'val3'};
console.log(object.count()); // 3

As a conclusion, if you want count functionality in objects, you need to copy the code from code block 1, and paste it early in execution time ( before you call the count ).

Let me know if that works for you!

Regards, Pedro

4 Comments

Hi. i have been using this for a while with no problems... the only issue I found is that if you loop on objects after impementing this property on all objects, it'll perform an extra loop. If anyone can find a workarround, that'd be great
huh? why not? someone might ifx it
IMO extending standard types isn't best idea
I agree, but our rubyist community might not. ;)
-4

Although it wouldn't be a "true object", you could always do something like this:

var foo = [
  {Key1: "key1"},
  {Key2: "key2"},
  {Key3: "key3"}
];

alert(foo.length); // === 3

1 Comment

We are trying to get the length of the property. So the result should be only 1 in your case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.