REACT transform a set into an object with assigned keys

Viewed 33

I need help transforming a set that constantly changes with a button click (it could have more components or less depending on how the user is filtering his options). The sets are successfully changing and saving the options in a useState constant

const [conditionFilter, setConditionFilter] = useState(new Set());

const [colorFilter, setColorFilter] = useState(new Set());

Here is how some sets may look like

//this is the output of conditionFilter
{
0: "isNew"
1: "isUsed"
}
// both sets may increase their size depending on the amount of filters selected

//this set is the output of colorFilter
{
0: "isBlack"
1: "isYellow"
2: "isGreen"
}

And this is my desired output

filtersSelected = {
 condition: ["isNew","isUsed"]
 color: ["isBlack", "isYellow", "isGreen"]
};
2 Answers

Say this is your condition object:

{
  0: "isNew",
  1: "isUsed"
}

and this is your color object:

{
  0: "isBlack",
  1: "isYellow",
  2: "isGreen"
}

Then:

filtersSelected = {
  condition = Object.values(condition),
  color = Object.values(color)
}

Should return your desired output.

thanks to Andre's solutions I realized that the set could stay as it is without making it an object with keys. And I came up with this solution to make the "allfilters" useState constant change when I need it

  const [allfilters, SetAllfilters] = useState({
    filter1: [""],
    filter2: [""],
  });
 const filtersSelected = () => {
    allfilters.filter1 = conditionFilter;
    allfilters.filter2 = colorFilter;
    SetAllfilters({ ...allfilters });
  };
  console.log(allfilters);

turns out the problem wasn't as complicated as I thought

Related