Search code examples
javascriptarraysformshandlebars.js

How to check if a Javascript object contains an array as a value for an attribute?


I have an object coming from the form data (in javascript using express handlebars), which can be as one of the following:

object1 = { name: "Grade1", section: "A", courses: [ "Eng", "Math", "Sci"] }

OR

object2 = { name: "Grade1", section: "A", courses: "Sci" }

How can I determine whether the courses attribute contains an array or a single value? Or is there a way to send the data from the form as an array for the attribute courses always (even if it is a single course)?

Thanks.


Solution

  • You can also use the isArray method. Note the documentation which explains why you may want to use this method as opposed to instanceOf:

    When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes.

    You may prefer this depending on your use case (assuming you're working with a browser) and gives you an opportunity to send it as an array if it isn't one already. Something like:

    var object1 = { name: "Grade1", section: "A", courses: [ "Eng", "Math", "Sci"] };
    var object2 = { name: "Grade1", section: "A", courses: "Sci" };
    
    console.log(object2.courses);
    
    if (!Array.isArray(object2.courses)) {
        object2.courses = [object2.courses];
     }
    
     console.log(object2.courses);