0
votes

I'm getting an error of 'collection' undefined when trying to push object.

groupShortlists(lists: ProductShortlist[]) {
    const grouped = lists.reduce((groupedList, list) => {
        groupedList[list.collection] = [...groupedList[list.collection] || [], list];
        return groupedList;
      }, {});

    return Object.keys(grouped).map(key => grouped[key]);
  }


this.shortlistsCategory = [];
this.groupShortlists(this.shortLists).map((item, key) => {
      this.shortlistsCategory.push({
        collection: item[key].collection,
        list: [],
      });
    });

The exact error says:

TypeError: Cannot read property 'collection' of undefined

Is this the proper way of using push. Any help would be appreciated. :D

1
In map function, the first arg will be a single obj/item of that array and the second will be index. So make sure item[0] exists.Yashwardhan Pauranik
What does groupShortlists do? Can you include a code snippet pleasechristian
Updated. I include what does groupShortlists do.raf
After seeing your snippet for the groupShortlist method, it looks like the returned array may have nested arrays (which could be an issue). Can you post an example of ProductShortlist?christian

1 Answers

1
votes

In this scenario, the item is already the value at the index key of shortLists. You can do either item.collection or shortLists[key].collection, but not both.

Also, using .map already returns the specified object, so there's no need to use .map and a .push (it's not as semantic).

Below is an example setting shortlists category to the .map return value.

this.shortlistsCategory = this.groupShortlists(this.shortLists)
  .map(item => {
    return {
      collection: item.collection,
      list: []
    };
  });

Link to .map docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map