Here is the original code
setRows((rows) =>
rows.map((row) =>
selected && row.node === selected.id
? { ...row, row.a: "",
row.b: "",
row.c: "" }
: row
)
);
I would have multiple properties inside row e.g., a, b, c, and so on. I have a constant named PosisbleValues containing name of those properties but how can i use it to iterate over while setting new values of row?
Currently, I'm using the following approach which is directly changing the state.
setRows((rows) => {
const row = rows.find(
(row) => selected && row.node === selected.id
);
if (row) {
PossibleValues.forEach(
(val) => (row[val] = "")
);
}
return rows;
});
Why do I want to do this? Because these properties a, b, c will increase/change in the future and I just want to change that in one file (i.e, where my PossibleValues const string array is residing).
CodePudding user response:
You could rewrite your first example like this:
setRows((rows) =>
rows.map((row) =>
selected && row.node === selected.id
? { ...row, ...{a: "", b: "", c: ""}}
: row
)
);
But {a: "", b: "", c: ""}
can be computed from the contents of PossibleValues
using Object.fromEntries(PossibleValues.map(key => ([key, ""]))
.
So the final code would be:
setRows((rows) =>
rows.map((row) =>
selected && row.node === selected.id
? { ...row, ...(Object.fromEntries(PossibleValues.map(key => ([key, ""])))}
: row
)
);