Categories
Mastering Development

Add matching values from one array to an array of original object

I have a users list like the following:

[
    {
        user: a,
        email: a.com,
        events: []
    },
    {
        user: b,
        email: b.com
        events: []
    }       
]

And an events list:

[
    {
        user: a,
        start: 2020-01-01
        end: 2020-01-02
    },
    {
        user: a,
        start: 2020-02-01
        end: 2020-02-02
    },    
    {
        user: b,
        start: 2020-03-01
        end: 2020-03-02
    },     
]

And I’m trying to combine the list of events by user into a array on the original users object like so:

[
    {
        user: a,
        email: a.com,
        events: [
            {
                start: 2020-01-01
                end: 2020-01-02
            },
            {
                start: 2020-02-01
                end: 2020-02-02
            }
        ]
    },
    {
        user: b,
        email: b.com,
        events: [
            {
                start: 2020-03-01
                end: 2020-03-02
            }
        ]
    }       
]

My original intuition is to simply iterate over the events list by each user and where they match by user value, push a new object to the users.events array. However, I’m not a JS pro, and I’m sure there’s a combination of assign/filter/map/reduce or lodash that streamlines this type of problem. Any help is greatly appreciated!

Leave a Reply

Your email address will not be published. Required fields are marked *