vzR vzR - 2 months ago 6
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...

Answer

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;
},{});

console.log(dailySchedule)
.as-console-wrapper {top : 0}

Comments