Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

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' ] 
}