我正在使用解析为JSON的xml。在特定情况下,如果节点包含多个子节点,则子节点存储在数组中。如果节点包含1个子节点,则它不存储在数组中。我需要能够检查子节点是否在数组中。我怎样才能做到这一点?
示例:
没有数组:
"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",
}
},
]
}
在' no array'例如,您可以看到childnode1不包含数组。在' with array'例如,childnode1包含一个包含多个子节点(1.1和1.2)的数组。
我尝试用
计算子节点var counter=0;
for(child in childnode1)
{ counter++; }
然而,这会产生意想不到的结果,例如,计数器不是' 1'什么时候没有数组。任何解决方案?
答案 0 :(得分:1)
虽然已经晚了。我认为这个代码对于查找对象中的子节点是否是数组非常有用 请检查以下代码段
var obj = {
"parentnode": {
"childnode1": {
"childnode1.1": {
"childnode1.1.1": "value here",
},
},
}
}
var count = 0;
checkForArrayObject(obj);
console.log(count);
var obj2={"parentnode":
{
"childnode1":
[
{
"childnode1.1":
{
"childnode1.1.1":"value here",
},
},
{
"childnode1.2":
{
"childnode1.2.1":"value here",
}
},
]
}};
count=0;
checkForArrayObject(obj2) ;
console.log(count);
function checkForArrayObject(obj) {
if (!(obj instanceof Object))
return count;
for (var key in obj) {
var value = obj[key];
var isArray = obj[key] instanceof Array;
if (!isArray) {
checkForArrayObject(value);
} else
count++;
}
}

希望这有帮助
答案 1 :(得分:0)
最安全的检查只是使用trincot所指出的Array.isArray(targetnode)
。
使用像.length这样的东西可能会起作用(假设节点总是一个对象或一个数组),但它不那么健壮,也不那么可读。
// 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));