Reputation: 471
I'm converting an xml string to json using php and then posting it to a
javascript file where I try to iterate it. When the object contains more than one object, json contains an array of objects like the first sample and I can iterate using the .length
function but when the object contains only 1 object an array is not being created and the .length
function fails. How can I make the iteration work in both cases without knowing the object's name?
Sample 1:
{"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
Sample 2:
{"class":
{
"name":"history",
"grade":"10"
}
}
Upvotes: 0
Views: 38
Reputation: 30473
You could check length
, and if it's undefined
it means it's just an object, then you make it an array with just one element:
if collection.length == undefined:
collection = [collection]
# the rest of the code doesn't need to be changed
Upvotes: 1
Reputation: 1484
You have to know the data type of the variable before knowing how to use .length
properly.
var dataTypeLength;
var data = {
"class":
{
"name":"history",
"grade":"10"
}
}
if (Array.isArray(data.class)) {
dataTypeLength = data.class.length;
} else {
dataTypeLength = Object.keys(data.class).length;
}
console.log(dataTypeLength);
Upvotes: 1
Reputation: 2770
You can check to see if the object is an array first: Array.isArray(obj)
. If it isn't then you know you don't need to iterate it.
var obj = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
if (!Array.isArray(obj)) return obj;
// else iterate it.
Upvotes: 1
Reputation: 4443
You can use for
for that and you don't need length
var test = {"class":[
{
"name":"history",
"grade":"10"
},
{
"name":"chemistry",
"grade":"8"
}
]
}
for (var i in test){
console.log(test[i]);
}
Upvotes: 1