i have object being created database call in following format:
object { group1={...}, same=null, group2=null}
i trying count of items in group1, group2, , same.
i accessed through console so:
dataobj.group1.length
in image above, returns undefined. however, if have more 1 item in group1
, returns count fine. appears cause issues when there single item in object/array.
is there function can used account these possibilities , return length
of items in objects above?
update:
this how creating data:
success: function(data) { // define our data response var d = data.data; // push our data 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, trying amount of items in same
, group1
, group2
.
this example of when more 1 item in response. able access using dataobj.group1.length
, returns 2
correct. trying figure out how handle when there 1
result.
after having question correctly explained me after head turned block of wood, it's case of covering eventualities. @kevinb correctly states, should sanitise response data returns array of objects, if there's 1 object or no objects in it. that's what's causing problem.
if response...
{ group1: { tool: 244, toolname: "blueprint" }, group2: null, same: null }
then group1
object, not array, therefore has no length
property. if, however, got response instead...
{ group1: [{ tool: 244, toolname: "blueprint" }], group2: null, same: null }
then group1
hold same data, array , therefore have length
property.
what suggest simple function evaluate objects , return expected response, this...
function getlength(obj) { if (obj == null) return 0; if (obj.length == undefined) return 1; return obj.length; }
in example, use getlength(dataobj.group1)
, return 1. return 0 if null
, return actual length if array.
Comments
Post a Comment