data.map is not a function

Total
0
Shares

I’m bashing my head against an error I can’t work out how to fix. I have the following;

JSON

{"products":
[
    {
        "product_id" : "123",
        "product_data" : {
            "image_id" : "1234",
            "text" : "foo",
            "link" : "bar",
            "image_url" : "baz"
        }
    },{
        "product_id" : "456",
        "product_data" : {
            "image_id" : "1234",
            "text" : "foo",
            "link" : "bar",
            "image_url" : "baz"
        }
    }
]}

and the following jQuery

function getData(data) {
    this.productID = data.product_id;
    this.productData = data.product_data;
    this.imageID = data.product_data.image_id;
    this.text = data.product_data.text;
    this.link = data.product_data.link;
    this.imageUrl = data.product_data.image_url;
}

$.getJSON("json/products.json").done(function (data) {

    var allProducts = data.map(function (item) {
        return new getData(item);
    });
});

yet I’m getting an error that map.data is undefined as a function? Looking at it I don’t know what’s not working as I’ve copied this to a new project from previously used code. The only thing different is the JSON source. The previous one didn’t have the {"products": part before the [] brackets. Is this what’s throwing me off?


Solution

Objects, {} in JavaScript do not have the method .map(). It’s only for Arrays, [].

So in order for your code to work change data.map() to data.products.map() since products is an array which you can iterate upon.

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *