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?
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?
Share Improve this question asked Sep 24, 2020 at 7:57 avydesignavydesign 1192 silver badges8 bronze badges 1- Are you using it for forms? – elpmid Commented Sep 24, 2020 at 8:00
5 Answers
Reset to default 13You 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/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);
In addition to @MorKadosh 's answer:
setClickColumn(Object.fromEntries(Object.entries(clickColumn)
.map(([key, value]) => [key, key === 'name' ? 2 : 1])))
You can easily create a function that will reset the state for you by parsing the object and give the right value:
const getResetClickColumn = (clickColumn) => {
Object.keys(clickColumn).forEach(key => {
const value = (key === 'name' ? 2 : 1);
clickColumn[key] = value;
})
return clickColumn;
}
const reset = getResetClickColumn({
name: 0,
tasks: 0,
partner: 0,
riskFactor: 0,
legalForm: 0,
foundationYear: 0
})
console.log(reset)
You can simply make a temp variable
let tmpColumn = clickColumn;
tmpColumn.name = 2;
// other changes
setClickColumn(tmpColumn);