I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories and locations for selection.
My current task involves extracting unique categories and counting how many times they appear, with the desired output being an array of objects structured like this:
[{title: 'Books', amount: 3 }, {title: 'Records', amount: 1 }, ...]
I suspect that the problem lies within the scope of my implementation.
Data
userData: {
items: [
{
itemName: 'test book',
category: 'Books',
location: 'Kitchen',
},
...
],
categories: ['Books', 'Movies', 'Records', 'Furniture'],
locations: ['Basement', 'Garage', 'Kitchen'],
},
I have managed to achieve the desired outcome for 'Books' but need assistance in generalizing it for all categories. Currently, my code displays the total count of items under the 'Books' category instead of displaying counts for each unique category.
The following method/function is where I'm struggling:
filteredItems = items.filter((item) => item.category === 'Books').length
In my logic, I need to find out what should replace the hardcoded 'Books' string in the filter function above for dynamic results across all categories.
For further clarity on the issue, please refer to the screenshot below:
https://i.stack.imgur.com/wwUpD.png
method/function
convertedCategories() {
const items = this.userData.items
const filteredItems = items.filter((item) => item.category === 'Books').length
function getItemCountOfCategory(categoryName) {
return filteredItems
}
function convertCategoriesIntoCards(categories) {
return categories.map((el) => {
return {
title: el,
amount: getItemCountOfCategory(el),
}
})
}
return convertCategoriesIntoCards(this.userData.categories)
}
If you need additional clarification or assistance regarding the specific line of code related to this query, please feel free to ask!