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