SBB SBB - 11 months ago 59
Javascript Question

Javascript/jQuery undefined object length

I have an object that is being created from a database call in the following format:

Object { group1={...}, same=null, group2=null}

enter image description here

I am trying to get the count of items in group1, group2, and same.

I accessed it through the console like so:


In the image above, this returns undefined. However, if I have more than one item in
, it returns the count just fine. It appears to only cause issues when there is a single item in the object/array.

Is there a function that can be used to account for these possibilities and return the
of items in those objects above?


This is how I am creating my data:

success: function(data) {

// Define our data response
var d =;

// Push our data to an object
dataObj = {
same: (d.same ? : null),
group1: (d.group1 ? : null),
group2: (d.group2 ? : null)

// Render our table

From here, I am trying to get the amount of items in

This is an example of when more than one item is in the response. I am able to access this using
and it returns
which is correct. All I am trying to figure out his how to handle this when there is only
enter image description here


After having the question correctly explained to me after my head turned into a block of wood, it's just simply a case of covering eventualities. As @KevinB correctly states, you should really sanitise the response data so it always returns an array of objects, even if there's only 1 object or even no objects in it. That's what's causing your problem.

If you get this response...

    group1: { tool: 244, toolName: "blueprint" },
    group2: null,
    same: null

then group1 is an object, not an array, so therefore has no length property. If, however, you got this response instead...

    group1: [{ tool: 244, toolName: "blueprint" }],
    group2: null,
    same: null

then group1 would hold exactly the same data, but would be an array and therefore have a length property.

What I would suggest is a simple function to evaluate the objects and return the expected response, like this...

function getLength(obj) {
    if (obj == null) return 0;
    if (obj.length == undefined) return 1;
    return obj.length;

In your example, you would use getLength(dataObj.group1) and it would return 1. It would return 0 if it was null and return the actual length if it were an array.