-1

Ok so I have a backbone model that is giving me the following array (or at least what I believe should be an array). Below is a screenshot of the console.log of my array.

enter image description here

So the array's name is myModel, and the following gives me an undefined value.

myModel.length

How can I go about getting the length of this array/Object so that I can loop over it?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Sean Peterson
  • 368
  • 4
  • 15

3 Answers3

1

What you have there could be an Array-like Object. The easiest thing to do is just to turn it into an Array. If you can use ES6 then your best option is Array.from(myModel).

If you can't use ES6 you can use Array.prototype.slice.call(myModel).

Both of these methods will turn your Array-like Object into an Array! (you do have to store the result in a variable)

DillGromble
  • 383
  • 2
  • 8
  • well that got rid of the undefined, however, it gives me an empty array – Sean Peterson Sep 21 '17 at 21:29
  • 1
    This wont mutate the object, instead will return a new array. So it should produce an array version of your data as long as you capture the output in something, or overwrite your object with the outputted array. – DillGromble Sep 21 '17 at 21:31
  • so I went myModel = Array.from(myModel); and the result was an empty array. I also tried this with the other solution ... unless I'm missing something here – Sean Peterson Sep 21 '17 at 21:37
  • 1
    According to any documentation I can find online, an Array-like Object has a `length` property - it's part of what makes it Array-like [1](http://2ality.com/2013/05/quirk-array-like-objects.html), [2](https://stackoverflow.com/questions/6599071/array-like-objects-in-javascript). – Kirk Larkin Sep 21 '17 at 21:38
  • @KirkLarkin So you are correct! I was mistaking the length to have gone the wayside with all the array methods. It must be just an Object then, but it is strange that it looks the way it does. In that case `for...in` is the best option – DillGromble Sep 21 '17 at 21:40
1

It looks like you're working with an Object rather than an Array. In this case, I think your Object has keys 0 - 4, making it look like an array.

You can use the for... in approach to iterate through the Object in the way you would expect. Of course, you can also use getOwnPropertyNames et al if you're worried about the prototype chain, but your example is fine as it's just a simple object.

Kirk Larkin
  • 84,915
  • 16
  • 214
  • 203
0

Well obviously that is just an object with array like properties such as;

var myModel = {0:"this", 1:"that"};

If you do;

var myArr = Array.from((myModel.length = Object.keys(myModel).length, myModel));

You will get a proper array like ["this", "that"].

Redu
  • 25,060
  • 6
  • 56
  • 76