AdrianDevera AdrianDevera - 1 month ago 8
Javascript Question

How to modify Properties of Objects within an Array

First note that this is a question from my Redux code HERE.

Okay so lets say I want to edit the property of 'status' from "pending" to "deleted" to a specific property of an object within an array, how would I be able to do this using Object.Assign for the following examples:

Example a: (notice the the array of objects is stored within an object itself)



const plan = {
task: [
{
id: 1,
description: "This is a task",
status: "pending"
},
{
id: 2,
description: "This is a second task",
status: "pending"
}
]
}





Example b: (A simple array of elements whose elements are objects)



const task2 = [
{
id: 1,
description: "This is a task",
status: "pending"
},
{
id: 2,
description: "This is a second task",
status: "pending"
}
]




Answer

NOTE I'm using the code from your first question

Ok so firstly in your renderList function you'll need to include an onclick handler to register when a task is done:

renderList() {
  return this.props.tasks.tasks.map((task) => {
    if(task.status == "pending"){
        return (
          <li key={task.id}>
            {task.id} {task.description}
            <button type="button">Finish</button>
            <button type="button">Edit</button>
            <button onClick={() => this.props.deleteTask(task.id)} type="button">Delete</button>
            </li>
          );
      }
  else return(
    <div key={task.id}>
      THIS TASK HAS BEEN DONE
    </div>
  );

}); }

Next, in your ActionIndex.js you should be recording WHICH action was selected, not just the message "deleted". SO change it to this:

export const deleteTaskAction = (taskId) => {
        return {
            type: 'DELETE_TASK',
            payload: taskId //pass on task id
        }
    };

Finally, in your reducer-tasks.js you should update the 'status' property of that specific list item when that action is dispatched (via the button click):

case 'DELETE_TASK':
    let newTasks = state.tasks.map( (task) => {
        if(task.id !== action.payload) {
            return task;
        }

        return Object.assign({}, task, {status : "deleted"});
    });

    const newState = Object.assign({}, state, {tasks : newTasks});
    return newState;

This should update the state and change the status of the selected task from "pending" to "deleted", which should trigger a re-render and change that element.

Let me know if you have any questions/issues