Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

jquery - data.map is not a function

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...