vzR vzR - 20 days ago 4x
Javascript Question

javascript: create an array of JSON objects from linking two arrays

let's say I have two arrays:

var meals: ["breakfast", "lunch", "dinner"];
var ingredients: [["eggs", "yogurt", "toast"],["falafel", "mushrooms", "fries"], ["pasta", "cheese"];

Is there an elegant solution to create an array of JSON objects which features:

var dailySchedule = {"breakfast" : ["eggs", "yogurt", "toast"],
"lunch": ["falafel", "mushrooms", "fries"],
"dinner": ["pasta", "cheese"]

I know it should be something with .reduce but I keep scratching my head how to do it...


Sure, you could reduce it

var meals = ["breakfast", "lunch", "dinner"];
var ingredients = [
  ["eggs", "yogurt", "toast"],
  ["falafel", "mushrooms", "fries"],
  ["pasta", "cheese"]

var dailySchedule = meals.reduce( (a,b, i) => {
	return a[b] = ingredients[i], a;

.as-console-wrapper {top : 0}