skip to Main Content

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


  1. 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 a forin loop, or map over the objects keys with Object.keys.

    This answer does a great job covering how to map over an object: https://stackoverflow.com/a/14810722/7638738

    Login or Signup to reply.
  2. groupBy is returning an object and .map is native to arrays. Using Object.keys, which is the equivalent of .map to iterate over an object.

    Check this answer out on how to make use of it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search