[英]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.