- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript: create an array of JSON objects from linking two arrays
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' ] }
Advertisements