I have the following State:
const [clickColumn, setClickColumn] = useState({
name: 0,
tasks: 0,
partner: 0,
riskFactor: 0,
legalForm: 0,
foundationYear: 0
})
And now, for example, I only want to set name to 2 and the rest to 1. But I do not want to write it this way: setClickColumn({ name: 2, tasks: 1, riskFactor: 1, partner: 1, legalForm: 1, foundationYear: 1 });
How can I make it shorter?
You can use spread operator to make it simple:
setClickColumn({ ...clickColumn, name: 2 });
it spreads the existing object clickColumn and adds the name: 2 to it, overriding the default value. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Making it shorter wouldn't necessarily make it more simple, but you can do something like this:
const obj = {
name: 0,
tasks: 0,
partner: 0,
riskFactor: 0,
legalForm: 0,
foundationYear: 0
};
const entries = Object.entries(obj).map(([key, value]) => key === 'name' ? [key, 2] : [key, 1]);
const result = Object.fromEntries(entries);
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With