data.map is not a function

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


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.


In some cases (not in all), the SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]) to change the items in the "data" into an array:

     $.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! enter image description here

Or convert "data" into an array in the following way:

     let dataArr = Array.from(data);

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

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

     });

But the very question here is to get the "products" out of the "data":

     data.products

The "products" is an array.

And then ".map" can be used:

     data.products.map

Tags:

Jquery

Json