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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented ProgrammingJSON

Suppose, we have two arrays like these −

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

We are required to write a JavaScript function that takes in two such arrays and maps the subarrays in the second array to the corresponding strings of the first array.

Therefore, the output for the above arrays should look like −

const output = {
   "breakfast" : ["eggs", "yogurt", "toast"],
   "lunch": ["falafel", "mushrooms", "fries"],
   "dinner": ["pasta", "cheese"]
};

Example

The code for this will be −

const meals = ["breakfast", "lunch", "dinner"];
const ingredients = [
   ["eggs", "yogurt", "toast"],
   ["falafel", "mushrooms", "fries"],
   ["pasta", "cheese"]
];
const combineMealAndIngredient = (meals, ingredients) => {
   const res = {};
   meals.forEach(function (el, ind) {
      this[el] = ingredients[ind];
   }, res);
   return res;
};
console.log(combineMealAndIngredient(meals, ingredients));

Output

And the output in the console will be −

{
   breakfast: [ 'eggs', 'yogurt', 'toast' ],
   lunch: [ 'falafel', 'mushrooms', 'fries' ],
   dinner: [ 'pasta', 'cheese' ]
}
raja
Published on 23-Nov-2020 15:13:30
Advertisements