I tried to group json data with specific key like that:
function groupBy(items) {
return items.reduce((acc, curr) => {
if (curr.league?.id) {
const { id } = curr.league;
const currentItems = acc[id];
return {
...acc,
[id]: currentItems ? [...currentItems, curr] : [curr]
};
}
return acc;
}, {});
}
console.log(groupBy(matches))
Then I get a correct result like that
but when I tried to get data using The map() method
like that :
groupBy(matches).map((match, index) => ( ..... ))
I get this error :
groupBy(...).map is not a function TypeError: groupBy(...).map is not a function
Any Idea?
2
Answers
Your
groupBy
function intakes an array, but returns an object. The.map
function is only available for arrays. To iterate over any object you can use aforin
loop, or map over the objects keys withObject.keys
.This answer does a great job covering how to map over an object: https://stackoverflow.com/a/14810722/7638738
groupBy
is returning an object and.map
is native to arrays. UsingObject.keys
, which is the equivalent of.map
to iterate over an object.Check this answer out on how to make use of it.