0

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

2 Answers2

1

If you just want to have a new resetData array with check: true for item with id: 5.

const resetData = optionsConsultation.map((item) => {
  if (item.id === 5) {
    return { ...item, check: true }
  }
  
  return item;
});

and if you want to rely only on index

const resetData = optionsConsultation.map((item, index) => {
  if (index === 4) {
    return { ...item, check: true }
  }
  
  return item;
});
Artem Matiushenko
  • 814
  • 10
  • 14
1

Changing values in nested objects/arrays could be really tedious.

If in your application you do it often I would like to recommend try using Immer (https://github.com/immerjs/use-immer).

Otherwise it's quite fine to do tike this:

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

or like this:

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

  return item;
});