Skip to main content

How do I count a JavaScript object"s attributes?



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?



Source: Tips4all

Comments

  1. There's no easy answer, because Object -- which every object in JS 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");


    EDIT: 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 JS besides this code, it could be higher than 4, if that other code also modifies the Object prototype.

    ReplyDelete
  2. 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 bevar object = {"key1":"value1","key2":"value2","key3":"value3"};

    ReplyDelete
  3. This was answered pretty well in another post:
    http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascript

    ReplyDelete
  4. 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;

    ReplyDelete
  5. 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

    ReplyDelete
  6. For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

    ReplyDelete
  7. 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

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex