0

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

4
  • 2
    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. Commented Nov 13, 2019 at 3:01
  • What does groupShortlists do? Can you include a code snippet please Commented Nov 13, 2019 at 3:50
  • Updated. I include what does groupShortlists do. Commented Nov 13, 2019 at 4:59
  • 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? Commented Nov 13, 2019 at 12:14

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.