JavaScript: 通过连接两个数组创建 JSON 对象的阵列
假设,我们有两个像这样的数组 −
const meals = ["breakfast", "lunch", "dinner"]; const ingredients = [ ["eggs", "yogurt", "toast"], ["falafel", "mushrooms", "fries"], ["pasta", "cheese"] ];
我们需要编写一个 JavaScript 函数,该函数接收两个此类数组并映射第二个数组中的子数组到第一个数组的相应字符串。
因此,以上数组的输出应如下所示 −
const output = {
"breakfast" : ["eggs", "yogurt", "toast"],
"lunch": ["falafel", "mushrooms", "fries"],
"dinner": ["pasta", "cheese"]
};示例
该代码如下 −
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));输出
控制台中的输出将如下所示 −
{
breakfast: [ 'eggs', 'yogurt', 'toast' ],
lunch: [ 'falafel', 'mushrooms', 'fries' ],
dinner: [ 'pasta', 'cheese' ]
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP