从嵌套对象中删除数据而不发生突变

Remove data from nested objects without mutating

本文关键字:突变 数据 嵌套 对象 删除      更新时间:2023-09-26

有没有优雅的方法可以从数组中删除对象,该数组是数组的一部分?我已经使用 React 和 Redux 一段时间了,但每次我必须在不改变状态的情况下删除或插入数据时都会卡住几个小时。

reducer 是一个数组,其中包含一个 ID 的对象和另一个包含对象的数组,如下所示:

[
 { id:123,
   items:[
           { id: abc,
             name: albert
           }, 
           ... 
         ]
 }, 
 ... 
]

我收到了两个 ID,需要删除 ID abc 的项目。

按 id 从数组中删除项目:

return state.filter(item => item.id !== action.id)

要按 id 从对象中删除键,请执行以下操作:

let copy = Object.assign({}, state) // assuming you use Object.assign() polyfill!
delete copy[action.id] // shallowly mutating a shallow copy is fine
return copy

(奖励)与对象传播运算符提案相同:

let { [action.id]: deletedItem, ...rest } = state
return rest
const remove = (state, bucketId, personId) => state.map(
  bucket => bucket.id === bucketId
    ? { ...bucket, items: bucket.items.filter(person => person.id !== personId) }
    : bucket,
);

用法:

const state = [
  {
    id: 123,
    items: [
      {
        id: 'abc',
        name: 'Kinna',
      },
      {
        id: 'def',
        name: 'Meggy',
      },
    ],
  },
  {
    id: 456,
    items: [
      {
        id: 'ghi',
        name: 'Ade',
      },
      {
        id: 'jkl',
        name: 'Tades',
      },
    ],
  },
];
console.log(remove(state, 123, 'abc'));

您可以使用下划线的拒绝。它完全符合您的要求。

如果你决定使用纯Javascript,我能想到的最优雅的方法是使用Array.prototype.reduce来减少状态:

var state = [
 { id: 123,
   items:[
           { id: 'abc',
             name: 'albert'
           }, 
           ... 
         ]
 }, 
 ... 
]
function filterOut (state) {
  return (bucketId, personId) => {
    return state.reduce((state, bucket) => {
      return state.concat(
        (bucketId === bucket.id) ?
          Object.assign({}, bucket, {items: bucket.items.filter((person) => person.id !== personId)}) :
          bucket
      );
    }, []);
  }
}
var newState = filterOut(state)(123, 'abc');

你也可以使用 lodash 的 omit 方法。

请注意,导入 lodash 会大大增加您的构建大小。通过仅导入特定方法来控制它: import omit from 'lodash/omit';

如果可能的话,我建议使用对象传播运算符,如Dan的答案中所述。

我以这种方式解决了我的问题

if(action.type === "REMOVE_FROM_PLAYLIST"){
        let copy = Object.assign({}, state) 
        delete copy.playlist[action.index].songs[action.indexSongs];
        return copy;
    }

希望它对其他人有所帮助。