最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I change only one value in a React useState that contains an object and assign a different one to the rest?

programmeradmin3浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 13

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/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);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论