I have an objects array:
[{description: a, category: a},{description: b, category: b},{description: c, category: c}...]
I need to restructure it to this format:
[{category: a, items: [a, b, c, d], priority: 1},{category: b, items: [a, b, c, d], priority: 2},{category: c, items: [a, b, c, d], priority: 10}]
What I did below works and returns the desired result, I'm just wondering if there is a way to shorten it.
const getNewList = items => {
// Filter items to get all categories and set their priority
let categories: any = [
...new Set(
items.map(item => {
switch (item.category.toLowerCase()) {
case 'a':
return {category: item.category, priority: 1}
case 'b':
return {category: item.category, priority: 2}
case 'c':
return {category: item.category, priority: 10}
}
})
)
]
// Remove duplicate entries
categories = [
...new Map(categories.map(item => [item.category, item])).values()
]
// Restructure object - get all items and the priority grouped by category
const newList = []
for (var i = 0; i < categories.length; i++) {
newList.push({
category: categories[i],
items: items
.filter(item=> item.category === categories[i].category)
.map(item=> {
return item.description
}),
priority: categories[i].priority
})
}
return newList
}
mapto create the new array.descriptionsthat match thecategory? in your example, i think i'm confused because it seems like the use of a,b,c,d might be a bit overloaded.Uncaught SyntaxError: unexpected token: ':'onlet categories: any = [