1

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

2
  • use a for(...) loop :) Commented Oct 2, 2016 at 20:52
  • 1
    JSON is text data, what you are after is plain JavaScript objects. Commented Oct 2, 2016 at 20:56

3 Answers 3

3

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}

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

Comments

0

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; }

Comments

0

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);

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.