简体   繁体   中英

Remove property for object in array

I have next code, where I need remove property unit from object Item in array Items :

Items.map(({ Item.unit, ...rest }) => {
     // some code
    return rest;
  });

But I am getting next error: Unexpected token., expected

You are not destructuring correctly.

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. You can either just use any parameter name in the callback function or destructure the object inside function's parameter list

If you use any parameter name as first argument to callback function, then you can remove the unit property as:

Items.map(item => {
     // some code
    const {unit, ...rest} = item;
    return rest;
});

but if you want to destructure the object in function's parameter list, then you need to do this as

Items.map(({ unit, ...rest }) => {
     // some code
    return rest;
});

what if I need 'Item' to access some other property?

all the properties of the currently destructured object, except unit property, will be available on rest object

You can delete it:

Items.map(item => {
    delete item.unit;
    return item;
});
Items.map(({unit, ...rest}) => {return rest});

You don't need to explicitly write return or event spread it while returning.


return Items.map(({unit, ...withoutUnit}) => withoutUnit)

You'll get a new array after this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM