Reputation: 195
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
Upvotes: 0
Views: 490
Reputation: 1705
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
Upvotes: 1