Search code examples
javascriptreactjsecmascript-6destructuringecmascript-next

Javascript ES6+: Destructuring and using an array method at the same time?


I was wondering if there is a way, to destructe and use an array method at the same time? If yes, is it useful to use it, or would it decrease the code readabilty so much, that it's not worth it?

My current code is this:

const { props: { title, ingredients: ing } } = this;
const ingredients = ing.map(
  (ing, index) => <li key={index}>{ing}</li>
);

But I'm trying to find a shorter way like this:

const { props: { title, ingredients: ingredients.map(
  (ing, index) => <li key={index}>{ing}</li>
); } } = this;

This code doesn't work though. Any tips would be much appreciated! :)


Solution

  • No, this is not possible. Destructuring does just that, it assigns properties to target expressions. Assignment syntax does not have any modifiers for altering the assigned value (default initialisers are already a stretch).

    As @kingdaro suggested, use

    const { title, ingredients } = this.props;
    const ingredientElements = ingredients.map((ing, index) => <li key={index}>{ing}</li>);