1

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

0

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can delete it:

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

1 Comment

This will also mutate the source array. There is little reason to keep using .map() in such case.
0
Items.map(({unit, ...rest}) => {return rest});

3 Comments

what if I need 'Item' to access some other property?
you can access other properties in 'rest'
Code-only answers are discouraged on SO. Most answers will benefit from an explanation to help visitors hone in on the important elements of your solution. Explanations increase long term value allowing uture visitors to learn from & apply your knowledge to their own code, keeps quality of SO high, & encourages the use of SO platform as a knowledge base, rather than a "give me the code" or, free coding service. Eplanations are usually quicker to digest/understand than strictly interpreting code, & helps distinguish your solution with other solutions. Well crafted answers are more often upvoted
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.