'using foreach inside map on array of object only changing the last record
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
}
}
Solution 1:[1]
Remove this else part:
else {
item.isChecked = false;
}
Solution 2:[2]
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);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kazi Mashry |
| Solution 2 | Carsten Massmann |
