Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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 JavaScript 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...

share|improve this question
    
use a for(...) loop :) – BeNdErR yesterday
1  
JSON is text data, what you are after is plain JavaScript objects. – vlaz yesterday
up vote 3 down vote accepted

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}

share|improve this answer

Just use Array#forEach.

The forEach() method executes a provided function once per array element.

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

meals.forEach(function (k, i) {
    this[k] = ingredients[i];
}, dailySchedule);        

console.log(dailySchedule);
.as-console-wrapper { max-height: 100% !important; top: 0; }

share|improve this answer

Another elegant way that i can think of is this;

var   meals = ["breakfast", "lunch", "dinner"],
ingredients = [["eggs", "yogurt", "toast"],["falafel", "mushrooms", "fries"], ["pasta", "cheese"]],
     result = Object.assign(...meals.map((m,i) => ({[m]:ingredients[i]})));
console.log(result);

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.