hampani
hampani

Reputation: 139

Append object into an array inside a object

NOTE: I'm open to other solutions. The objective of this code is to easily get all events on a particular day by accessing it with a date. This might not be the greatest solution.

I want to push an "event" object into the correct array however I can't get it to work.

Below is the object that I want to "add" to.

this.state = {
    events: {
        Wed Apr 14 2021 00:00:00 GMT+0200 (Central European Summer Time): [],
        Tue Apr 15 2021 00:00:00 GMT+0200 (Central European Summer Time): [],
        and so on....
    }
}

The "date-key"'s time is always the same (00:00:00 GMT+0200 (Central European Summer Time)) however not the day, month, or year.

And here is my attempt to get this to work:

addEvent(event) {
        const events = this.state.events;
        const date = event.date;
        let list = [];

        if (typeof events[date] !== 'undefined') {
            list = events[date];
        }

        list.push(event);
        //console.log(events[date]);

        this.setState({
            events: {
                [date]: list
            }
        });
    }

(The event parameter that is passed in is an object with a "new Date()" attribute as event.date.)

Upvotes: 0

Views: 62

Answers (2)

Yadab
Yadab

Reputation: 1883

You can do something like this. Based on the latest comment you have made.

addEvent(event) {
        const { events } = this.state;
        const date = event.date.getTime();
        let list = [];

        if (typeof events[date] !== 'undefined') {
            list = events[date];
        }

        list.push(event);
        //console.log(events[date]);

        this.setState((state) => ({
            events: {
                ...state.events,
                [date]: list,
            },
        }));
    }

Remember to create a date if your event.date is not type of Date.

addEvent(event) {
        const { events } = this.state;
        const date = new Date(event.date)

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 282030

Maintain an array for days in a way you store them in events state lie

let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

Now you can use the date.getUTCDay() or date.getDay() function depending on whether date in in UTC for or not to extract the day and then update it in your state

addEvent(event) {
    const events = this.state.events;
    const dayOfWeek = days[event.date.getUTCDay()];
    let list = [];

    if (typeof events[dayOfWeek ] !== 'undefined') {
        list = events[dayOfWeek];
    }

    list.push(event);
    this.setState({
        events: {
            ...this.state.events,
            [dayOfWeek]: list
        }
    });
}

Upvotes: 1

Related Questions