简体   繁体   中英

Using Object.keys(), map(), …Array(), reduce() and concat() in a single const

I'm learning React.js on Udemy. We wrote a long stateless component which used Object.keys() , map() , ...Array , reduce() and concat() in a single const.

I know every method we used in this stateless component. But when I used them all in a single component I lost a track.

Like why did we put [] on reduce() method as second parameter or what does (_, i) is for on map() method?

Can you explain this code step by step?

const burger = (props) => {

     let transformedIngredients = Object.keys( props.ingredients )
      .map( igKey => {

         return [...Array( props.ingredients[igKey] )].map( (_, i) => {
            return <BurgerIngredient key={igKey + i} type={igKey} />;
         });
      }) 
     .reduce((arr, el) => {
          return arr.concat(el);
     }, []);
 Object.keys( props.ingredients )

retrieves an array of ingredients names.

 .map( igKey => {

maps that array to a new array, were each element contains

 [...Array( props.ingredients[igKey] )]

an array that has as many entries as the value related to the ingredient in the passed object.

 .map( (_, i) => {

then maps that inner array, ignores the value (which is undefined for an empty array anyways) and only takes the index and maps it to

      <BurgerIngredient key={igKey + i} type={igKey} />;

Now we do have a 2D array of BurgerIngredients, and

 .reduce((arr, el) => {
      return arr.concat(el);
 }, []);

flattens that to an array of BurgerIngredients. Reducing means that we start with the initial value ( [] ) and .concat every value (inner array) of the original array to it.


I'd write that as:

 const Burger = ({ ingredients }) => {
   const list = [];

   for(const [ingredient, amount] of Object.entries(ingredients)) {
     for(let count = 0; count < amount; count++) {
        list.push(<BurgerIngredient key={ingredient + count} type={ingredient} />);
     }
  }

  return <div className="burger">
    Ingredients:
    {list}
  </div>;
};

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