如何用扩展运算符与解构从对象中删除指定项并拆分剩余内容?
使用解构赋值与扩展运算符删除对象中的指定项
原始代码(存在问题)
interface Item { id: string; title: string, } interface ItemState { entities: { [id: string]: Item }; } const toBeDeleted = { id: '2', title: 'item_2' }; const state: ItemState = { entities: { '1': { id: '1', title: 'item_1' }, '2': { id: '2', title: 'item_2' }, '3': { id: '3', title: 'item_3' } } }; const { [toBeDeleted.id]: deleted, ...remaingEntities } = state; // 此处有误 const newState = { entities: remaingEntities }; // 期望达成的效果: // deleted.toBe( { id: '2', title: 'item_2' } ) // newState.toBe( { // entities: { // '1': { id: '1', title: 'item_1' }, // '3': { id: '3', title: 'item_3' } // } // })
问题描述
我希望用扩展运算符和解构赋值,把state拆成两部分:
- 要删除的目标项
- 剩余的所有项
本质是取出state.entities['2'],同时保留其余内容。想问这种方式是否可行?是不是我混淆了概念?
解决方案
你的思路完全可行,只是解构的目标对象搞错了。你现在解构的是整个state对象,但state本身只有entities一个属性,并没有'2'这个键——你要操作的是state.entities这个内部对象。
修正后的代码如下:
interface Item { id: string; title: string, } interface ItemState { entities: { [id: string]: Item }; } const toBeDeleted = { id: '2', title: 'item_2' }; const state: ItemState = { entities: { '1': { id: '1', title: 'item_1' }, '2': { id: '2', title: 'item_2' }, '3': { id: '3', title: 'item_3' } } }; // 改为解构 state.entities,而不是 state const { [toBeDeleted.id]: deleted, ...remaingEntities } = state.entities; const newState = { entities: remaingEntities }; // 此时结果完全符合预期: // deleted 等于 { id: '2', title: 'item_2' } // newState 等于 { entities: { '1': {...}, '3': {...} } }
原理说明
- 解构赋值语法
{ [key]: target, ...rest } = obj会从obj中提取key对应的属性赋值给target,同时把剩下的所有属性自动收集到rest对象中。 - 因为我们要操作的是
state内部的entities对象,所以必须把解构目标指向state.entities,而非外层的state。
内容的提问来源于stack exchange,提问作者edd
相关产品推荐
相关产品推荐

