Home > Software design >  using foreach inside map on array of object only changing the last record
using foreach inside map on array of object only changing the last record

Time:04-06

I'm trying to use forEach inside a .map to change all the isChecked property in the checkedState variable according to data variable. but somehow it only changes the last row. what am I doing wrong? any help is appreciated

this is my code

const listHari = [
  { nama: "senin", nomor: 1, isChecked: false },
  { nama: "selasa", nomor: 2, isChecked: false },
  { nama: "rabu", nomor: 3, isChecked: false },
  { nama: "kamis", nomor: 4, isChecked: false },
  { nama: "jumat", nomor: 5, isChecked: false },
  { nama: "sabtu", nomor: 6, isChecked: false },
  { nama: "minggu", nomor: 7, isChecked: false },
];

const AddRute = () => {
  const [checkedState, setCheckedState] = useState(listHari);

  const getRuteById = async () => {
    const data = [
      {id: "2", nama: "selasa", hari: "2"}, 
      {id: "4", nama: "kamis", hari: "4"}, 
      {id: "5", nama: "jumat", hari: "5"}
    ];

    const tmp1 = checkedState.map((item, index) => {
      console.log("index", index);

      data.forEach(function (row) {
        const rowHari = row.hari - 1;
        if (index === rowHari) {
          item.isChecked = true;
        } else {
          item.isChecked = false;
        }
        console.log("hari", rowHari, item.isChecked);
        // console.log('ischecked', item.isChecked);
      });

      return item;
    });
    console.log("temp", tmp1); // ==> in tmp1, only the 5th item has isChecked true
  }
}

CodePudding user response:

Remove this else part:

else {
  item.isChecked = false;
}

CodePudding user response:

Here is another way of checking the desired elements in listHari:

const listHari = [
  { nama: "senin", nomor: 1, isChecked: false },
  { nama: "selasa", nomor: 2, isChecked: false },
  { nama: "rabu", nomor: 3, isChecked: false },
  { nama: "kamis", nomor: 4, isChecked: false },
  { nama: "jumat", nomor: 5, isChecked: false },
  { nama: "sabtu", nomor: 6, isChecked: false },
  { nama: "minggu", nomor: 7, isChecked: false } ], 
 data = [
  { id: "2", nama: "selasa", hari: "2"}, 
  { id: "4", nama: "kamis", hari: "4"}, 
  { id: "5", nama: "jumat", hari: "5"}
 ];
 
 listHari.forEach(lh=>data.some(d=>lh.isChecked=d.id==lh.nomor));
 
 console.log(listHari);

  • Related