So I'm trying to make an array with different properties for each day of the week.
I have this array:
const [fullData, setFullData] = useState([{index:-1,exercise:""}])
So when user clicks on Monday for instance, I have a bunch of exercises for him to choose. For each exercise I want to put the index of the weekday( I already have this in my code) lets say 1 and the exercises that he chose.
It would end up with something like:
[{index:1,exercise:"exercise1"},{index:1,exercise:"exercise2"}]
I'm not really sure how to do this cause I have the exercises already in an array:
const [exerciseValues, setExerciseValues] = useState([]);
And my weekday is just a regular variable
let selectedWeekday_Index:number;
I tried a bunch of examples listed in stackoverflow already but I could implement it to my code, can anybody help me out? My last try ended up with this code - that does not work. If anyone needs more details to understand just ask me and I will update the question with it.
const acceptExercises = () => {
let selectedElements = [...exerciseValues]
let savedData = [...fullData]
selectedElements.forEach(element => {
let copyData=savedData.map(item=>({
[item.exercise]:element,
[item.index]:selectedWeekday_Index
}))
setFullData(copyData)
});
}
CodePudding user response:
I would also recommend saving your data in a different way like @iz_ mentioned.
But If you still want to do it that way you can make use of this implementation of setting your fullData
:
const acceptExercises = () => {
setFullData((prev) => [
...prev,
...exerciseValues.map((exercise) => ({
index: selectedWeekday_Index,
exercise: exercise,
})),
]);
};
First we copy the previous values via prev
, then we map through the exerciseValues
and get a list of exercises
with the correct week index, which we spread and add to the fullData
.