My array
const initial_business_hours = [
{ "day": "Sunday", "open_time": "Not set", "close_time": "Not set" },
{ "day": "Monday", "open_time": "Not set", "close_time": "Not set" }
]
Saved in a state
const [business_hours, setBusinessHours] = useState(initial_business_hours);
The switch toggle state
const [isSundaySwitchOn, setIsSundaySwitchOn] = useState(true);
Logic for removing/filtering object from array
const onToggleSundaySwitch = () => {
setIsSundaySwitchOn(!isSundaySwitchOn)
if (JSON.stringify(business_hours).includes(JSON.stringify({ "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }))) {
const updatedBusinessHours = business_hours.filter(item => item.day !== business_hours[0].day)
return setBusinessHours(updatedBusinessHours)
}
setBusinessHours([...business_hours, { "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }])
};
What is happening
Initial switch state is true/on. What happens is that when I toggle off the switch, it removes the desired object { "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }
. This is so far okay.
Current array state:
[{"close_time": "Not set", "day": "Monday", "open_time": "Not set"}]
If I toggle on the switch, it adds the { "day": "Sunday", "open_time": "Not set", "close_time": "Not set" }
again. This again is a desired behavior.
Current array state:
[{"close_time": "Not set", "day": "Monday", "open_time": "Not set"},
{"close_time": "Not set", "day": "Sunday", "open_time": "Not set"}]
But on the next toggle off, what was removed is now the { "day": "Monday", "open_time": "Not set", "close_time": "Not set" }
Current array state:
[{"close_time": "Not set", "day": "Sunday", "open_time": "Not set"}]
On the next toggle on, the array is now empty.
[]
If I toggle it off again, the array is now:
[{"close_time": "Not set", "day": "Sunday", "open_time": "Not set"}]
If I toggle it on again, the array is empty again:
[]
And it continues to the behavior that it adds the "Sunday" object again, then empty, then "Sunday" on every toggle.
What I’m trying to achieve is for this scenario:
I know the error is somewhere inside the filter()
, I just can’t seem to figure it out.
Does it have something to do with the actual filter()
and it’s filtering condition item => item.day !== business_hours[0].day
and .includes()
?
Thank you for your help, I am a beginner when it comes to array manipulation.
2
Answers
You need to change your code to this
In your code
what you were doing with this above line is filtering out the first object. No matter if it is sunday or monday.
business_hours[0]
picks first object in that array. It does not check if it is sunday or monday or something else.You can use something like given below.