如何更改对象?

时间:2018-10-25 15:11:06

标签: javascript arrays reactjs object redux

如何使用点差更改对象?

export const list = [
    {
        id: 0,
        tableName: 'example',
        tasks: [
            {
                task_id: 0, 
                task_short: 'lorem',
                task_full: 'lorem ipsum lorem ipsum lorem ipsum',
                time_created: null,
                time_changed: null, 
            },
            {
                task_id: 1, 
                task_short: 'andsf',
                task_full: 'lorem ipsum tes tes est',
                time_created: null,
                time_changed: null, 
            }
        ]
    }
]

矿山有效载荷具有三个属性

case 'CHANGE_TASK':
        ///////update, ownId, parentId

例如,在更新中,我更改了任务[0]

在此之后,我无法解决如何更改和返回列表

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作来实现所需的功能。

但是我可以保证这不是最佳实践,

保持状态正常化,不要嵌套对象。

const list = [{
  id: 0,
  tableName: 'example',
  tasks: [{
      task_id: 0,
      task_short: 'lorem',
      task_full: 'lorem ipsum lorem ipsum lorem ipsum',
      time_created: null,
      time_changed: null,
    },
    {
      task_id: 1,
      task_short: 'andsf',
      task_full: 'lorem ipsum tes tes est',
      time_created: null,
      time_changed: null,
    }
  ]
}]

const parentId = 0;

const ownId = 1;

const update = {
  task_short: 'Updated andsf',
  task_full: 'Updated lorem ipsum tes tes est',
}

const newList = list.map(item => {
  if (item.id === parentId) {
    return {
      ...item,
      tasks: item.tasks.map(task => {
        if (task.task_id === ownId) {
          return {
            ...task,
            ...update,
          }
        }
        return task;
      })
    }
  }
  return item;
})

console.log(newList)

答案 1 :(得分:0)

我会像这样使用减速器组成:

const list = [{
  id: 0,
  tableName: 'example',
  tasks: [{
      task_id: 0,
      task_short: 'lorem',
      task_full: 'lorem ipsum lorem ipsum lorem ipsum',
      time_created: null,
      time_changed: null,
    },
    {
      task_id: 1,
      task_short: 'andsf',
      task_full: 'lorem ipsum tes tes est',
      time_created: null,
      time_changed: null,
    }
  ]
}]

const topReducer = (state, action) => {
  switch (action.type) {
    case "UPDATE_TASK":
      return state.map(listReducer(action));
    default:
      return state;
  }
}

const listReducer = action => state => {
  if (action.id !== state.id) {
    return state;
  }
  switch (action.type) {
    case "UPDATE_TASK":
      return {
        ...state,
        tasks: state.tasks.map(taskReducer(action))
      }
    default:
      return state;
  }
}

const taskReducer = action => state => {
  if (action.task_id !== state.task_id) {
    return state;
  }
  switch (action.type) {
    case "UPDATE_TASK":
      return { ...state,
        ...action.update
      };
    default:
      return state;
  }
}

const action = {
  type: "UPDATE_TASK",
  task_id: 0,
  id: 0,
  update: {
    task_short: 'ipsum',
  }
}

console.log(topReducer(list, action))