1

I am trying to construct an array based on two separate arrays such as the following example:

const breakfast = [
   { dishId: 23, name: 'Pasta'}
]

const ingredients = [
   // ...
   { ingrId: 13, name: 'Tomato' },
   { ingrId: 29, name: 'Beef' }
]

// connecting table
const breakfastDishIngredients = [
   { id: 1, dishId: 23, ingrId: 13 },
   { id: 1, dishId: 23, ingrId: 29 }
]

The new array should be the breakfast array with an additional ingredients key for every element. Like this:

const newBreakfast = [
   { dishId: 23, name: 'Pasta', ingredients: [
                { ingrId: 13, name: 'Tomato' },
                { ingrId: 29, name: 'Beef' }
              ]}
] 

I am trying the following but its not working:

let newBreakfast = []

for(let i in breakfastDishIngredients) {
    _breakfast = breakfast.map(item => {
        return { ...item, ingredients: ingredients.filter(el => item.id === breakfastDishIngredients[i][0].dish_id && el.id === breakfastDishIngredients[i][0].ingredient_id) }
    })
}

I appreciate any help.

4 Answers 4

1

const breakfast = [
   { dishId: 23, name: 'Pasta'}
];
const ingredients = [
   // ...
   { ingrId: 13, name: 'Tomato' },
   { ingrId: 29, name: 'Beef' }
];
const breakfastDishIngredients = [
   { id: 1, dishId: 23, ingrId: 13 },
   { id: 1, dishId: 23, ingrId: 29 }
];

let newBreakfast=breakfast.map(
  dish=>(
    {
      dishId:dish.dishId, name:dish.name, ingredients:
      breakfastDishIngredients.filter(
        ingredient=>ingredient.dishId==dish.dishId
      ).map(
        filtered=>(
          ingredients.filter(
            ingredient=>ingredient.ingrId==filtered.ingrId
          )
        )
      ).flat()
    }
  )
)

console.log(newBreakfast);

Sign up to request clarification or add additional context in comments.

2 Comments

you were right on what i actually meant, however this is returning ingredients as an array of arrays :/
it is close, we need ingredients to be an array of objects.
1

Try this:

const breakfast = [
   { dishId: 23, name: 'Pasta'}
]

const ingredients = [
   // ...
   { ingrId: 13, name: 'Tomato' },
   { ingrId: 29, name: 'Beef' }
]

// connecting table
const breakfastDishIngredients = [
   { id: 1, dishId: 23, ingrId: 13 },
   { id: 1, dishId: 23, ingrId: 29 }
]

const result = breakfast.map(br => {
  const ingredientsFiltered = breakfastDishIngredients
                                .filter(brDiIngr => brDiIngr.dishId === br.dishId)
                                .map(el => ingredients.find(ingr => ingr.ingrId === el.ingrId));
  return { ...br, ingredients: ingredientsFiltered };
});

console.log(result);

2 Comments

sorry, i updated the question, the final array should be: const newBreakfast = [ { dishId: 23, name: 'Pasta', ingredients: [ { ingrId: 13, name: 'Tomato' }, { ingrId: 29, name: 'Beef' } ]} ]
OK. Updated answer.
0

you can do something like this

const breakfast = [ { dishId: 23, name: 'Pasta' } ];

const ingredients = [
    // ...
    { ingrId: 13, name: 'Tomato' },
    { ingrId: 29, name: 'Beef' }
];

// connecting table
const breakfastDishIngredients = [ { id: 1, dishId: 23, ingrId: 13 }, { id: 1, dishId: 23, ingrId: 29 } ];

const newBreakfast = [
    {
        dishId: 23,
        name: 'Pasta',
        ingredients: [ { ingrId: 13, name: 'Tomato' }, { ingrId: 29, name: 'Beef' } ]
    }
];

let result = breakfast.map((item) => ({ ...item, ingredients: ingredients }));
console.log(result);

1 Comment

ingredients are connected to dish - if/when there will be other dishes and more ingredients, your solution will list all ingredients to every dish.
0

Solution with Reducer and some utils for more reusability.

const breakfast = [
   { dishId: 23, name: 'Pasta'}
]

const ingredients = [
   // ...
   { ingrId: 13, name: 'Tomato' },
   { ingrId: 29, name: 'Beef' }
]

// connecting table
const breakfastDishIngredients = [
   { id: 1, dishId: 23, ingrId: 13 },
   { id: 1, dishId: 23, ingrId: 29 },
   { id: 1, dishId: 24, ingrId: 29 }
]

//utils
const lookUp = idString => arr => targetId => arr.filter(el => el[idString] == targetId)

// FP specialization
const lookUpIngrId = lookUp("ingrId")(ingredients);
const lookUpDishId = lookUp("dishId")(breakfast);

const getFirstOneOrNull = arr => Array.isArray(arr) && arr.length === 1 ? arr[0] : null;

//reducer
const reducerBreakFast = (acc, currentValue) => {
  const id = getFirstOneOrNull(lookUpDishId(currentValue.dishId))
  if(!id){
    return acc;
  }
  const ingrValue = getFirstOneOrNull(lookUpIngrId(currentValue.ingrId))
  acc.has(id) ? acc.set(id, [...acc.get(id), ingrValue]) : acc.set(id, [ingrValue])
  return acc;
}

const mapNewBreakfast = breakfastDishIngredients.reduce(reducerBreakFast, new Map())

const mapToArray = dataMap => Array.from(dataMap.keys()).map(key => ({
  ...key,
  ingredients: dataMap.get(key)
}))

const newBreakfast = mapToArray(mapNewBreakfast);

Output:

{
  dishId: 23,
  name: 'Pasta',
  ingredients: [ { ingrId: 13, name: 'Tomato' }, { ingrId: 29, name: 'Beef' } ]
}

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.