vzR vzR - 1 year ago 75
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 Source

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}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download