Sunday

An example of converting object to an array in javascript


const ingredients = {
 salad: 2,
 tomato: 1,
 cheese: 3,
 meat: 2
}

const transformedIngredients = Object.keys(ingredients)
  .map(iKey => {
     return [...Array(ingredients[iKey])].map((_, i) => {
       return iKey ;
   });
}); 

console.log(transformedIngredients.toString());
the output is: salad,salad,tomato,cheese,cheese,cheese,meat,meat

**Object.keys(ingredients) returns key list:   salad,tomato,cheese,meat
**Array(ingredients[iKey])   returns the value of the given key like salad. for instance,the output for salad: Array(2). so the second map loops 2 time and returns salad twice.

No comments:

Post a Comment