I am building javascript (nodejs) integration with a remote service. The service returns inconsistently formatted results, and from within javascript, I am battling to determine how to switch my formatting based on the response.
The 2 formats are shown below, the first is when Parent has a single child, and the 2nd is where Parent has >1 children:
var single = { "Parent" : { "name" : "foo" } }
var multi = { "Parent" : [ { "name" : "foo" }, { "name" : "bar" } ] }
So when I try and parse the results in js, accessing a child attribute of “name”, I get inconsistent results:
for (var i in single) {
console.log("child name: " + single[i].name;
}
for (var i in multi.Parent) {
console.log("child name: " + multi.Parent[i].name;
}
What would the best way be to determine whether I am getting a single or multi result back? I tried “typeof response”, hoping to get an “Array” for multi, but that didn’t work.The object is initially received as a string, but converted to an object using JSON.parse(responseString).
You could probably use
constructorproperty.