max pleaner max pleaner - 3 months ago 13
Javascript Question

Array not responding to forEach

Here's some test in my Chrome dev console:

> tags
returns ["test_tag", "test_tag2"]

> tags.forEach
returns undefined

> ["test_tag", "test_tag2"].forEach
returns forEach() { [native code] }


I have no idea why my
tags
object is not responding to
forEach
.

Checking the type is not very instructive, which is to be expected:

> typeof(tags)
// returns 'object'
> typeof(["test_tag", "test_tag2"])
// returns 'object'


How am I constructing this
tags
object?

var $nodes = $(".metadata")
var tags = $nodes.map(function(idx, node){
nodeJson = $(node).text()
return JSON.parse(nodeJson)['tags']
})

Answer

jQuery's map() function returns the collection of elements, or in this case the returned text wrapped in a jQuery object, which is of course an object, not an array.

If you wanted the text in an array, you'd use get() as well

var $nodes = $(".metadata")
var tags = $nodes.map(function(idx, node){
    var nodeJson = $(node).text();
    return JSON.parse(nodeJson)['tags'];
}).get();

or the more appropriate $.map

var $nodes = $(".metadata")
var tags = $.map( $nodes, function(node){
    var nodeJson = $(node).text();
    return JSON.parse(nodeJson)['tags'];
});
Comments