daxidngyn
daxidngyn

Reputation: 59

Adding an object to an array contained inside an object without overriding

I am currently trying to loop through an array of objects (each object is a task), where each task contains relevant information such as a name and date. Information from each task is then utilized in creating an object containing arrays, where each array contains objects that correspond to the date, or the array.

My current code is as follows:

contextTasks.forEach((taskItem) => {
  taskItem["taskSchedule"].forEach((dateItem) => {
    setItems((items) => ({
      ...items,
      [dateItem["date"]]: [
        {
          name: taskItem["taskName"],
          time: new Date(dateItem["time"]).toLocaleTimeString([], {
            hour: "2-digit",
            minute: "2-digit",
          }),
          type: "Task",
        },
      ],
    }));
  });
});

However, if there are multiple tasks with the same date, they will override each other and I only end up with one task per date. How would I go about pushing further objects to the array if there are other entries for that specific date?

Finished object:

Object {
  "2021-04-21": Array [
    Object {
      "name": "Test Class v1",
      "type": "Class",
    },
  ],
  "2021-04-24": Array [
    Object {
      "name": "Test Task v2",
      "type": "Task",
    },
    //I would like to add another object here without overriding existing contents of the array
  ],
}

Upvotes: 0

Views: 51

Answers (2)

Karim Chaari
Karim Chaari

Reputation: 402

Have you tried using reduce ?

the idea will be to have something like this inside your accumulator: {"date1": [{val}, {val}, ...] , "date2": [{val}, {val}, ...]}

array.reduce((acc, val) => {
// test if your accumulator has the same date as your date from the val
if(acc[val.date]) {
 acc[val.date] = [... acc[val.date], ...your val] 
} else {
// no date found in the accumulator so make acc.date = ...acc.date, val
acc[val.date] = [ val ]
}

}, {})

Sorry if the code is not perfect but if you want provide your initial array of data and I will fix the response code

Upvotes: 1

Patryk Cieszkowski
Patryk Cieszkowski

Reputation: 751

The cause of your issue is the fact you're executing an async method inside a synchronous loop. Also, modifying state forces a re-render, and you're attempting to do it presumably many times at once. It might, and will cause a bottleneck at some point.

The solution: build your new state first, and execute a setState once.

Upvotes: 1

Related Questions