首页 > 解决方案 > Change List of objects in position using map for Reactjs

问题描述

I would like to know how to change the item 'check' to true from position 5 on my array list.

const optionsConsultation = [
  { label: "Maçã", check: false, id: 0, disable: false },
  { label: "Banana", check: false, id: 1, disable: false },
  { label: "Pera", check: false, id: 2, disable: false },
  { label: "Uva", check: false, id: 3, disable: false },
  { label: "Morango", check: false, id: 5, disable: false},
  { label: "Laranja", check: false, id: 6, disable: false }
];

export default () => {
  const [datas, setDatas] = useState(optionsConsultation);

  useEffect(() =>{
    const resetData = datas.map(checks => checks)
    )

标签: javascriptreactjs

解决方案


更改嵌套对象/数组中的值可能非常乏味。

如果在您的应用程序中您经常这样做,我建议您尝试使用 Immer ( https://github.com/immerjs/use-immer )。

否则这样做很好:

//
const targetItemIndex = 5;
const resetData = [
  ...datas.slice(0, targetItemIndex),
  { ...datas[targetItemIndex], check: true },
  ...datas.slice(targetItemIndex + 1)
];
//

或像这样:

const targetItemIndex = 5;
const resetData = datas.map((item, index) => {
  if (index === targetItemIndex) {
    return { ...item, check: true };
  }

  return item;
});

推荐阅读