SBB SBB - 4 months ago 27
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:

dataObj.group1.length


In the image above, this returns undefined. However, if I have more than one item in
group1
, 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
length
of items in those objects above?

Update:

This is how I am creating my data:

success: function(data) {

// Define our data response
var d = data.data;

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

// Render our table
renderCompare();
}


From here, I am trying to get the amount of items in
same
,
group1
,
group2
.

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

Answer

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.