Reputation: 3377
I'm using a node module that returns some data. The data will be returned in one of two ways:
single record
single = {"records[]":{"name":"record1", "notes":"abc"}}
multiple records
multiple = {"records[]":[{"name":"record1", "notes":"abc"},{"name":"record2", "notes":"xyz"}]}
If I call the following I can get the value from single records
single['records[]'].name // returns "record1"
for multiple records I would have to call like this
multiple['records[]'][0].name // returns "record1"
problem occurs when I get back a single record but treat it as multiple
single['records[]'][0].name // returns undefined
right now I test like this:
var data = nodemodule.getRecords();
if(data['records[]'){ //test if records are returned
if(data['records[]'].length){ //test if 'records[]' has length
// ... records has a length therefore multiple exist
// ... for loop to loop through records[] and send data to function call
} else {
// .length was undefined therefore single records
// single function call where I pass in records[] data
}
}
Is this the best way to test for single vs multiple records given that I'm under the constraints of what the node module returns or am I missing some easier way?
Upvotes: 0
Views: 75
Reputation: 3452
You can use Array.isArray(obj)
obj The object to be checked.
true if the object is an Array; otherwise, false.
if(data['records[]']){
if(Array.isArray(data['records[]'])){
// console.log('multiple');
}else{
// console.log('single');
}
}
https://stackoverflow.com/a/26633883/4777670 Read this it has some faster methods.
Upvotes: 1