The "TypeError: map is not a function" occurs when we call the map() method on an object that is not an array. To solve the error, console. log the value you're calling the map() method on and make sure to only call the map method on valid arrays.
If one element in the domain mapped with more then one element in the range, the mapping is called one-to-many relation. One-to-many relations are not functions. Example: Draw a mapping diagram for the function f(x)=2x2+3 in the set of real numbers.
map() function will not work with objects. You will need to enclose your object in an array. Make a simple change to your state within the parent component: Change movies: "" to movies: [] .
map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.
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.
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
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!
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
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);
});
If you want to map an object you can use Lodash. Just make sure it's installed via NPM or Yarn and import it.
With Lodash:
Lodash provides a function _.mapValues
to map the values and preserve the keys.
_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });
// => { one: 3, two: 6, three: 9 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With