如何删除嵌套对象的数组中的对象

时间:2019-07-10 17:39:43

标签: arrays reactjs object

我有一个包含数据的表:

enter image description here 当我单击删除按钮时,我知道具有此数据的索引和用户ID。 我想从“ timeRecords”数组中删除该对象,并在没有它的情况下返回“ employeeList”。

enter image description here

我尝试实现此功能,但没有结果

//recordId = index and key also, userID = userId who have this records.
  deleteRecord = (recordID, userID) => {  
    console.log(`usunięto rekord: ${recordID}, na użytkowniku o ID: ${userID}`);
    let employeesList = this.state.employeesList;
    employeesList = employeesList.filter(el => {
      if (el.id === userID) {
        if (el.timeRecords !== recordID) {
          return el.timeRecords;
        }
      }
    });
  };

3 个答案:

答案 0 :(得分:2)

您可以像这样使用.map()和嵌套的.filter()来删除已标识的对象。 .map()用于迭代雇员对象。找到具有匹配ID的员工后,我们将遍历其timeRecords以过滤出要删除的员工:

deleteRecords = (recordId, userId) => {
  const { employeesList } = this.state
  const newArr = employeesList.map((item) => {
    if(item.id == userId){
        return {
            ...item,
            timeRecords: item.timeRecords.filter((record) => record.id !== recordId)
        }
    } else {
        return item
    }
  })
}

运行以下示例:

var array = [{id: 1, timeRecords: [{id: 5, hours: 2}, {id: 6, hours: 3}]}, {id: 2, timeRecords: [{id: 7, hours: 2}, {id: 8, hours: 3}]}]

const deleteRecords = (recordId, userId) => {
  const newArr = array.map((item) => {
    if(item.id == userId){
        return {
            ...item,
            timeRecords: item.timeRecords.filter((record) => record.id !== recordId)
        }
    } else {
        return item
    }
  })
  
  console.log(newArr)
}

deleteRecords(5, 1)

答案 1 :(得分:0)

[{
  accountNumber: "1111111",
  id: 1,
  timeRecords: [{
    id: 0,
    hours: '1'
  }, {
    id: 1,
    hours: '2'
  }, {
    id: 2,
    hours: '3'
  }]
}]

解决方案,可能看起来过度设计,但这是突变的正确方法

deleteRecord = (recordID, userID) => {  
    const list = this.state.employeesList;
    const index = list(v => v.id === userID)
    const nestedList = list[index].timeRecords
    const nestedIndex = nestedList.findIndex(v => v.id === recordID)
    return [
      ...list.slice(0, index), // get items before the userID
      {
        ...list[index], // fill other pros of userID
        timeRecords: [ // remove item by recordID
          ...nestedList.slice(0, nestedIndex),
          ...nestedList.slice(nestedIndex + 1)
        ]
      },
      ...list.slice(index + 1) // get items after the userID
    ]
  }

答案 2 :(得分:0)

因此,您要从特定用户权限中删除特定时间记录吗?您可以映射用户,如果id不匹配,则可以立即转到该用户,如果他们匹配,则可以过滤时间记录并以此更新用户。

deleteRecord = (recordID, userID) => {
  return employeesList.map(employee => {
    if (employee.id !== userID) return employee;

    const timeRecords = employee.timeRecords.filter(
      timeRecord => timeRecord.id !== recordID
    );

    return { ...employee, timeRecords };
  });
};