I am trying to make a function as re-usable as possible.
I have a JSON file containing "products" for now.
export let productList = [
{
id: 0,
productName: "Men's Merrel Hiking Boots",
price: 65.00,
brand: "Merrell",
},
{
id: 1,
productName: "Women's Merrel Hiking Boots",
price: 65.00,
brand: "Merrell",
},
{
id: 2,
productName: "Natural Walking Stick",
price: 22.00,
brand: "Fayet",
}
]
In my case, I am trying to map through these products and return all the brands without duplicates. I know I can do that with this Set function:
function dedupeCheckboxOptions() {
return [...new Set(productList.map(product => product.brand))];
}
This works, but I am struggling to figure out a way to make this more re-usable. I would think it would look something like this so I could also use the function to maybe return the prices:
function dedupeCheckboxOptions(fullList, item) {
return [...new Set(fullList.map(product => product.item))];
}
However, this syntax is not correct. Is there a way to accomplish this?
Update:
function dedupeCheckboxOptions(fullList, item) {
return [...new Set(fullList.map(product => product[item]))];
}
This looks promising from what @samathingamajig said, but when I pass through the productList
from the JSON file and run the app (React app), it says the productList
is undefined.