3

I have a javascript object that contains 6 objects that may contain additional arrays or objects. Using javascript or jquery, how can I quickly count number of these 6 top level objects

1   Object { salesman="1714, name="Lucien Layton", events={...}}
2   Object { salesman="1715", name="Hugo Hayne", events={...}}
3   Object { salesman="17165", name="Jonas Jessie", events={...}}
4   Object { salesman="1718", name="Ezequiel Ebner", events={...}}
5   Object { salesman="1721", name="Randolph Rodda", events={...}}
6   Object { salesman="1722", name="Edwin Earles", events={...}}
1
  • If you don't need support to older browsers you can use Object.keys(yourObj).length, otherwise a simple for..in loop should be enough Commented Jul 28, 2013 at 21:32

1 Answer 1

5

You could do this...

var objectsLength = 0;
for ({}[++objectsLength] in objects) {}

jsFiddle.

It's kind of funky, but also cool. Still, due to its unusualness, I'd just suggest the more common method...

var objectsLength = 0;
for (var prop in objects) {
    objectsLength++;
}

jsFiddle.

If you're unsure about your environment and think they're might be iterable properties on the prototype chain, use hasOwnProperty() (or create your objects with Object.create(null)).

If browser support is in your favour...

var objectsLength = Object.keys(objects).length;

jsFiddle.

Sign up to request clarification or add additional context in comments.

10 Comments

Interesting solution. Just keep in mind the numeric keys will be enumerated if you have to iterate the properties again for some reason.
Even more interesting: after the for..in loop, an object like {foo: 1, bar: 2, baz: 3} becomes {1: "foo", 2: "bar", 3: "baz", foo: 1, bar: 2, baz: 3} - but nothing on that code says the values of the new numeric keys should be the original keys!
It happens with every type of object, this is very strange! For example an object {a: "b", c: "d"} becomes {1: "a", 2: "c", a: "b", c: "d"}.
The cause seems to be: in for prop in obj, prop is assigned the key name. So objects[++objectsLength] in that position actually means objects[++objectsLength] = keyname. I never saw that in js before, very interesting behavior! I will try to dig deeper.
@bfavaretto The placement does. The left side expression is always set to the key name by Call PutValue(lhsRef, P), apparently whether it's a single variable or uses a member operator.
|

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.