-1

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.

Mitchell
  • 111
  • 15

1 Answers1

0

Use the bracket notation property accessor since you're using a variable.

Also, you don't need to pass in individualItem because that already gets defined when you set that as the name of the argument passed into the callback function.

function dedupeCheckboxOptions(productList, item) {
    return [...new Set(productList.map(individualItem => individualItem[item]))];
}
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • When you eventually call this function, how do you pass the variables? I tried `dedupeCheckboxOptions(productList, product, brand)`, but product and brand are always "not defined" – Mitchell Feb 09 '23 at 05:30
  • @Mitchell you would call this like `dedupeCheckboxOptions(productList, "brand")`, unless you have a variable called `brand` with the value of `"brand"`, or any of the other keys – Samathingamajig Feb 09 '23 at 05:33
  • Any ideas on why the returned result is "Cannot read properties of undefined (reading 'map')"? – Mitchell Feb 09 '23 at 05:36
  • @Mitchell because `productList` is `undefined` – Samathingamajig Feb 09 '23 at 05:42
  • Sorry, the variable name should have been something like `reusableList`. The name of my imported set of product data is `productList`. It should contain the full list of products – Mitchell Feb 09 '23 at 05:44