0

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?

1
  • 1
    looks good to me, if there's no other requirements - always better to keep things simple. Commented Jun 29, 2018 at 15:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.