[英]Remove property for object in array
我有下一个代码,我需要从数组Items
中的 object Item
中删除属性unit
:
Items.map(({ Item.unit, ...rest }) => {
// some code
return rest;
});
但我收到下一个错误: Unexpected token., expected
您没有正确解构。
As you map over the Items
array, each object in Items
array will be passed as first argument to the callback function of map
function. 您可以在回调 function 中使用任何参数名称,也可以在函数的参数列表中解构 object
如果您使用任何参数名称作为回调 function 的第一个参数,则可以将unit
属性删除为:
Items.map(item => {
// some code
const {unit, ...rest} = item;
return rest;
});
但是如果你想在函数的参数列表中解构 object,那么你需要这样做
Items.map(({ unit, ...rest }) => {
// some code
return rest;
});
如果我需要“项目”来访问其他属性怎么办?
当前解构的 object 的所有属性,除了unit
属性,将在rest
object 上可用
你可以delete
它:
Items.map(item => {
delete item.unit;
return item;
});
Items.map(({unit, ...rest}) => {return rest});
您无需在返回时显式编写返回或事件传播它。
return Items.map(({unit, ...withoutUnit}) => withoutUnit)
之后你会得到一个新数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.