2

I've been looking for an answer to this one, but can't seem to find any, I apologize if there already is one.

I expect an object, let's say something like this:

{
    name: 'myname',
    items: [
        {
            itemID: '1'
        },
        {
            itemID: '2'
        },
        {
            itemID: '3'
        }
    ]
}

The problem is that whenever there is only one object inside "items", it looks like this:

{
    name: 'myname',
    items: {
        itemID: '1'
    }
}

This means that my forEach function will break, since "items" is no longer an array of objects. There is a lot of data and things done inside each "items" object in the forEach so I prefer not having to use both forEach and another function, but rather convert it to an array and only use forEach.

This is what I want to do:

if (items is not array) {
    //Convert the object to this:
    {
        name: 'myname',
        items: [
            {
                itemID: '1'
            }
        ]
    }
}

I have problems to determine if items is an array of objects or just an object (in both cases typeof items will return "object"), and also how to convert it to an array if it's not an array. Very grateful for help or tips

  • 2
    You can use something like this http://stackoverflow.com/questions/4775722/check-if-object-is-array, or if you are using jQuery then `$.isArray`. – mic4ael Oct 04 '15 at 07:22
  • or something like this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray – Simone Nigro Oct 04 '15 at 07:23
  • 1
    I highly recommend you to keep the format of the object which I suspect is the response from server of an API to be constant whether there is one element or more. If you've no control over API, then you've to iterate over the object and check if the element is an array or object. – Tushar Oct 04 '15 at 07:27
  • downvote with no comment has my upvote – Simone Nigro Oct 04 '15 at 07:31
  • @SimoneNigro Why? This is a poorly researched duplicate. – Sebastian Simon Oct 04 '15 at 07:32
  • 1
    Even if it is a duplicate, the question was asked well enough. The vote should be to close, not a downvote. I'll also have to upvote to offset that downvote, but also vote to close. – vol7ron Oct 04 '15 at 07:33
  • @SimoneNigro Please read http://meta.stackexchange.com/questions/74666/is-voting-to-balance-in-the-spirit-of-the-site – Tushar Oct 04 '15 at 07:34
  • Possible duplicate of [How do you check if a variable is an array in JavaScript?](http://stackoverflow.com/questions/767486/how-do-you-check-if-a-variable-is-an-array-in-javascript) – vol7ron Oct 04 '15 at 07:34
  • @vol7ron right! vote it's only for the quality of content and this question it's not bad. – Simone Nigro Oct 04 '15 at 07:40
  • @Tushar ok, but we must try to be more friendly to newbie – Simone Nigro Oct 04 '15 at 07:43
  • 1
    Yes, you can tear me to shreds, but be kind to the newbies ;) – vol7ron Oct 04 '15 at 07:44

3 Answers3

1

You can wrap the item with an array if needed, for Example:

(Array.isArray(obj.items) ? obj.items : [obj.items]).
   forEach(function(item){

     .
     .
     .

   });
CD..
  • 72,281
  • 25
  • 154
  • 163
  • 1
    This is a good one-liner answer, but Andreas may have difficulty in understanding the notation w/o explanation: CD is using a ternary to always return the times as an array and immediately iterating over that array using the `forEach` syntax. The `.` on the end of the ternary operation is important because it is the dot-notation sigil that tells the JS engine that `forEach` is a property or method of the array. – vol7ron Oct 04 '15 at 07:40
1

Use Array.isArray(obj) for check if a var is an array

eg:

var object1 = {
  name: 'myname',
  items: [{
    itemID: '1'
  }, {
    itemID: '2'
  }, {
    itemID: '3'
  }]
};

var object2 = {
  name: 'myname',
  items: {
    itemID: '1'
  }
};


if (Array.isArray(object1.items)) {
  document.write('Hey guy I\'m an array!<br />');
} else {
  document.write('Hey guy I\'m not an array!<br />');
}

if (Array.isArray(object2.items)) {
  document.write('Hey guy I\'m an array!<br />');
} else {
  document.write('Hey guy I\'m not an array!<br />');
}
Simone Nigro
  • 4,717
  • 2
  • 37
  • 72
1

I'm only offering this in addition to the other answers because I don't think they are clear enough.

var items = obj.items;
if( ! Array.isArray(items) ){
   items = [items];
}

items.forEach(function(){
   // iterate over each item
});

These steps can be combined as seen in CD..'s answer

Community
  • 1
  • 1
vol7ron
  • 40,809
  • 21
  • 119
  • 172