data.map is not a function

后端 未结 9 1036
轮回少年
轮回少年 2020-12-02 05:50

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         


        
相关标签:
9条回答
  • 2020-12-02 06:23

    data needs to be Json object, to do so please make sure the follow:

    data = $.parseJSON(data);
    

    Now you can do something like:

    data.map(function (...) {
                ...
            });
    

    I hope this help some one

    0 讨论(0)
  • 2020-12-02 06:24
    this.$http.get('https://pokeapi.co/api/v2/pokemon')
    .then(response => {
       if(response.status === 200)
       {
          this.usuarios = response.data.results.map(usuario => {
          return { name: usuario.name, url: usuario.url, captched: false } })
              }
        })
    .catch( error => { console.log("Error al Cargar los Datos: " + error ) } )
    
    0 讨论(0)
  • 2020-12-02 06:25

    data is not an array, it is an object with an array of products so iterate over data.products

    var allProducts = data.products.map(function (item) {
        return new getData(item);
    });
    
    0 讨论(0)
  • 2020-12-02 06:26

    There is an error on $.map() invocation, try this:

        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.json?sdfsdfg").done(function (data) {
    
            var allPosts = $.map(data,function (item) {
    
                for (var i = 0; i < item.length; i++) {
                    new getData(item[i]);
                };
    
            });
    
        }); 
    

    The error in your code was that you made return in your AJAX call, so it executed only one time.

    0 讨论(0)
  • 2020-12-02 06:29

    The right way to iterate over objects is

    Object.keys(someObject).map(function(item)...
    Object.keys(someObject).forEach(function(item)...;
    
    // ES way
    Object.keys(data).map(item => {...});
    Object.keys(data).forEach(item => {...});
    

    Read here for details

    0 讨论(0)
  • 2020-12-02 06:30

    The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):

         $.getJSON("json/products.json").done(function (data) {
    
             var allProducts = [data].map(function (item) {
                 return new getData(item);
             });
    
         });
    

    Here, [data] is an array, and the ".map" method can be used on it. It works for me!

    0 讨论(0)
提交回复
热议问题