Create Array of JSON Objects by Linking Two Arrays in JavaScript



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' ] }
Updated on: 2020-11-23T10:43:43+05:30

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close