1

i have been trying doing so but in the last console log I got undefined , what is wrong??

 dishes = dishes.map((cat) => {
      cat.map((dish) => {
        console.log("cat", dish[0], "dish", dish[1]);
         dish[1].map((element) => {
          element = { ...element, category: dish[0] };
        });
      });
    });

    console.log("dishes",dishes)

2 Answers 2

1

You are forget return the map result

 dishes = dishes.map((cat) => {
  return cat.map((dish) => {
    console.log("cat", dish[0], "dish", dish[1]);
    return dish[1].map((element) => ({ ...element,
      category: dish[0]
    }))
  });
});

Still undefined check the dishes array declared properly before the map

var dishes = [something]
Sign up to request clarification or add additional context in comments.

Comments

0

You have to return something in your map callbacks. When using arrow functions, you don't necessarily need to include the return keyword, though. In cases where you only need to return the result of an expression, you can remove the body brackets and the return. For example: const addOne = a => { return a + 1 } can be simplified to just const addOne = a => a + 1.

In your case, the logic might look something more like:

const categories = [
  [ 'category 1', [
    { name: 'dish 1' },
    { name: 'dish 2' },
  ] ],
  [ 'category 2', [
    { name: 'dish 3' },
  ] ],
]

const dishesWithCategory = categories.flatMap(
  ([ category, dishes ]) => dishes.map(dish => ({ ...dish, category }))
)

console.log('dishes', dishesWithCategory)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.