i have a an array mapping action looking like this :
this.itemsList= res.map( ( x, index ) => {
x.id = x.code;
x.itemName = x.name;
return x;
} );
I ve tried to optimize it like this (2nd manner):
this.itemsList = res.map(({code: id, name: itemName}) => ({id, itemName}));
but i need to return each mapped element of the array (return x
)
i wonder how to do it using my optimized manner (2nd)
ideas ??
You can use the ...
spread operator to spread the remaining object properties into a value, and the use the spread operator again to spread those properties from the stored object back into the target object.
res.map(({ code: id, name: itemName, ...otherProps }) => ({
id, itemName, ...otherProps,
}));
Note that this does remove the original code
and name
properties. If you still need those, you'll have to add them explicitly as well.
res.map(props => ({
id: props.code,
itemName: props.name,
...props,
}));
When you say filter
I believe you are referring to the plucking of specific properties -- in this case using destructuring. This is different than the collection filter
operation which removes elements from a collection based on the result of a projected function.