Home > Mobile >  sorting through objects in arrays, adding if none exist, else replace existing
sorting through objects in arrays, adding if none exist, else replace existing

Time:06-08

I have time slots like 9:00, 9:10, 9:20, etc. What I am trying to achieve is that when the person edits the task of that slot and clicks the button, then the task{} object is built with the timeDeclared and the info. then the task{} is added into an array if the array does not contain the timeDeclared already, if it does, it gets replaced by the new info. The goal of this is for me to then save the array into the memory that way when the page loads I can load the array from memory and place the tasks in the time slots they belong.

current outcome = it keeps getting replaced

wanted outcome = checks for existing time slot object in the array, add if it does not exist, replace if it does

$("li").on("click", "button", function () {
    let wrap = $(this).parents("li");
    let info = $(wrap).find("p").text().trim();
    let timeDeclared = $(wrap).find(".slotMinutes").text().trim();
    var task = {};
    task.time = timeDeclared;
    task.info = info;
    var tasks = [];
    add(tasks, timeDeclared)

    function add(tasks, time) {
        const found = tasks.some(el => el.time === timeDeclared);
        if (!found) tasks.push({ task });
        return tasks;
    }

    console.log(add(tasks));

    tasks.push(task)
    localStorage.setItem("data", JSON.stringify(tasks))
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

You can try run a for loop in the array with all tasks, and check if some task have this TimeDeclared equal.

Something like this:

let tasks = [{ info: 'task1_info', time: '9:00' },{ info: 'task2_info', time: '9:30' },{ info: 'task3_info', time: '10:00' }];

function add(tasks, time) {
    let newTaskArray = [];
    let hasNewTask = false;

    for(let i=0; i < tasks.length; i  ) {
        if(tasks[i].time == time) {
                newTaskArray.push({info:'newtask_info', time:time})
                hasNewTask = true;
        } else {
            newTaskArray.push({info:tasks[i].info, time:tasks[i].time})

            // This piece only run when hasn't a new task added and it was the last task from the loop
            if(!hasNewTask && i   1 == tasks.length) {
                newTaskArray.push({info:'newtask_info', time:time})
                
            }
        }
    }
    console.log(newTaskArray);
}

add(tasks, '9:00')

CodePudding user response:

$('li').on('click', 'button', () => {
  // Extract data from localStorage, initialize it if it does not exists
  let tasks = localStorage.getItem('data');
  if (!tasks) {
    tasks = [];
  }
  // Create task object
  const wrap = $(this).parents('li');
  const info = $(wrap).find('p').text().trim();
  const timeDeclared = $(wrap).find('.slotMinutes').text().trim();
  const task = {
    time: timeDeclared,
    info: info
  };
  // Add or overwrite task object
  const index = tasks.findIndex(object => {
    return object.time === timeDeclared;
  });
  if (index == -1) {
    tasks.push(task);
  } else {
    tasks[index] = task;
  }
  // Update storage data
  localStorage.setItem('data', tasks);
});
  • Related