Home > Net >  How to handle object which is created by groupBy function at once?
How to handle object which is created by groupBy function at once?

Time:11-12

I have a object which is created by groupBy function.

const productOptions = {
    color: [
        { id: 1, type: "color", name: "red" },
        { id: 2, type: "color", name: "orange" },
        { id: 3, type: "color", name: "yellow" },
    ],
    size: [
        { id: 4, type: "size", name: "sm" },
        { id: 5, type: "size", name: "md" },
        { id: 6, type: "size", name: "lg" },
        { id: 7, type: "size", name: "xl" },
    ],
};

To display product options by type, I hardcoded it like below.

<ProductOption productOptionType={"color"} productOptions={productOptions.color} />
<ProductOption productOptionType={"size"} productOptions={productOptions.size} />

In the future, weight, accessory, and more will be added to type.

I hate this static structure. Is there a way to display it dynamically using productOptions object at once??

I tried with .map(), But object's keys are not accessible.

I also tried with for-in loop, It doesn't render well.

How can I solve this???

CodePudding user response:

Use Object.keys to loop over keys, then you can dynamically render as many as you want. So render this:

Object.keys(productOptions).map(key => (
    <ProductOption productOptionType={key} productOptions={productOptions[key]} />
))

CodePudding user response:

You could use Object.keys here

Object.keys(productOptions).map((item)=>(
  <ProductOption productOptionType={item} productOptions={productOptions[item]} />
)
  • Related