ILE ILE - 1 month ago 5
Javascript Question

How to check if childnode of Javascript object contains array

I'm working with xml parsed as JSON. In a specific situation, if a node contains several childnodes the childnodes are stored in an array. If a node contains 1 childnode it's not stored in an array. I need to be able to check if the childnodes are in an array or not. How can I do this?

Example:

no array:

"parentnode":
{
"childnode1":
{
"childnode1.1":
{
"childnode1.1.1":"value here",
},
},
}


with array:

"parentnode":
{
"childnode1":
[
{
"childnode1.1":
{
"childnode1.1.1":"value here",
},
},
{
"childnode1.2":
{
"childnode1.2.1":"value here",
}
},
]
}


In the 'no array' example, you can see that childnode1 does not contain an array. In the 'with array' example, childnode1 contains an array with multiple childnodes (1.1 and 1.2).

I tried counting childnodes with

var counter=0;
for(child in childnode1)
{ counter++; }


however this generates unexpected results, for example counter is not '1' when there is no array. Any solutions?

Answer

The safest check would be simply to use Array.isArray(targetnode) as noted by trincot.

Using something like .length could would work (with assumptions that nodes are always either an object or an array), but it would be less robust and not as readable.

// no array
var object1 = {
  "parentnode":
  {
    "childnode1":
    {
        "childnode1.1":
        {
            "childnode1.1.1":"value here",
        },
    },
  }
};

// has array
var object2 = {
  "parentnode":
  {
    "childnode1":
    [
        {
            "childnode1.1":
            {
                "childnode1.1.1":"value here",
            },
        },
        {
            "childnode1.2":
            {
                "childnode1.2.1":"value here",
            }
        },
    ]
  }
};
      
console.log("Object1 has Array? " + !!object1.parentnode.childnode1.length);
console.log("Object2 Has Array? " + !!object2.parentnode.childnode1.length);

console.log("Object1 has Array? " + Array.isArray(object1.parentnode.childnode1));
console.log("Object2 Has Array? " + Array.isArray(object2.parentnode.childnode1));

Comments