4

Possible Duplicate:
Array length undefined

I have the following array but whenever I try to find out the length with categoryData.length it gives me only undefined. If I type console.log(categoryData) it gives me all the objects in the array.

var categoryData = {
animals: {
    name: "Animals",
    description: "All your favorites from aardvarks to zebras.",
    items: [
        {
            name: "Pets"
        },
        {
            name: "Farm Animals"
        },
        {
            name: "Wild Animals"
        }
    ]
},
colors: {
    name: "Colors",
    description: "Fresh colors from the magic rainbow.",
    items: [
        {
            name: "Blue"
        },
        {
            name: "Green"
        },
        {
            name: "Orange"
        },
        {
            name: "Purple"
        },
        {
            name: "Red"
        },
        {
            name: "Yellow"
        },
        {
            name: "Violet"
        }
    ]
},
vehicles: {
    name: "Vehicles",
    description: "Everything from cars to planes.",
    items: [
        {
            name: "Cars"
        },
        {
            name: "Planes"
        },
        {
            name: "Construction"
        }
    ]
}

};

Community
  • 1
  • 1
Tudor Ravoiu
  • 2,130
  • 8
  • 35
  • 56

1 Answers1

16

That's because categoryData is not an Array - it's an Object. And while some JS objects (arguments, for example) support length property, those created with object literal notation do not.

You can count your object's length by yourself, with this:

function countProps(obj) {
    var count = 0;
    for (var p in obj) {
      obj.hasOwnProperty(p) && count++;
    }
    return count; 
}

This can be done even in a more simple way, if your target environment supports (or has it shimmed) the Object.keys method:

function sizeObj(obj) {
  return Object.keys(obj).length;
}

... and that's exactly how it's done in Underscore.js library method:

_.size = function(obj) {
    if (obj == null) return 0;
    return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • Thank you. Using aside of this http://stackoverflow.com/a/17818507/2480481 you can use it with no problem. I used directly `Object.keys(document.getElementsByTagName("audio")).length;`, and worked perfectly. U can take a look of my js audio controller gist at https://gist.github.com/erm3nda/f105cc80a478c641ca527f13866c5f4d – m3nda Jun 03 '16 at 16:09
  • worked in node.js too thank you @raina77ow – Iftikar Urrhman Khan Jun 15 '16 at 18:45