JavaScript:通过链接两个数组创建一个 JSON 对象数组

javascriptweb developmentfront end technologyobject oriented programmingjson

假设我们有两个像这样的数组 −

const meal = ["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' ]
}

相关文章