Lotherad
Lotherad

Reputation: 125

Converting object to array

I'm getting list of elements but it is object when I want it to be array. I got simply code like this:

var obj = document.getElementsByClassName('_54nc');
var arr = $.map(obj, function(value, index) { return [value]; });
console.log(typeof arr);

And console is saying "object". How do I convert this?

Upvotes: 0

Views: 55

Answers (1)

Lew
Lew

Reputation: 1278

In javascript, typeof an array is object. One way you can check if you are getting an array is to look at the constructor of the object:

possibleArray.constructor == Array

If this condition returns true then you have yourself an array.

It is also worth mentioning that you have mixed plain javascript with jQuery. You could improve your code by simply having the following:

var arr = $('._54nc')

You can then use arr[0] to get the first element or arr[1] to get the second and so on.

arr will be an array like object, which in javascript, support numeric subscripting.

Upvotes: 2

Related Questions