JavaScript:2つの配列のリンクからJSONオブジェクトの配列を作成します
次のような2つの配列があるとします-
const meals = ["breakfast", "lunch", "dinner"]; const ingredients = [ ["eggs", "yogurt", "toast"], ["falafel", "mushrooms", "fries"], ["pasta", "cheese"] ];
このような2つの配列を受け取り、2番目の配列のサブ配列を最初の配列の対応する文字列にマップする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' ]
} -
JavaScriptJSON配列
JSONの配列は、JavaScriptの配列に似ています。 JavaScriptJSON配列は次のようになります- let obj = { name:'Rohan', sports : ['cricket','Football','volleyball','hockey'] } 以下はJavaScriptのJSON配列のコードです- 例 <!DOCTYPE html> <html lang="en"> <head
-
JavaScriptを使用してJSON配列からデータを読み取る方法は?
以下は、JavaScriptを使用してJSON配列からデータを読み取るためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style