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

การจัดการข้อมูลด้วย JavaScript

สมมติว่าเรามีอาร์เรย์สองอาร์เรย์ที่อธิบายกระแสเงินสดดังนี้:

const months = ["jan", "feb", "mar", "apr"];
const cashflows = [
  {'month':'jan', 'value':10},
  {'month':'mar', 'value':20}
];

เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์สองอาร์เรย์ดังกล่าว ฟังก์ชันควรสร้างอาร์เรย์รวมของอ็อบเจ็กต์ที่มีอ็อบเจ็กต์สำหรับแต่ละเดือนและค่ากระแสเงินสดของเดือนนั้น

ดังนั้น สำหรับอาร์เรย์ข้างต้น ผลลัพธ์ควรเป็นดังนี้:

const output = [
  {'month':'jan', 'value':10},
  {'month':'feb', 'value':''},
  {'month':'mar', 'value':20},
  {'month':'apr', 'value':''}
];

ตัวอย่างโค้ด

โค้ดสำหรับทำสิ่งนี้คือ:

const months = ["jan", "feb", "mar", "apr"];
const cashflows = [
  {'month':'jan', 'value':10},
  {'month':'mar', 'value':20}
];
const combineArrays = (months = [], cashflows = []) => {
  let res = [];
  res = months.map(function(month) {
    return this[month] || { month: month, value: '' };
  }, cashflows.reduce((acc, val) => {
    acc[val.month] = val;
    return acc;
  }, Object.create(null)));
  return res;
};
console.log(combineArrays(months, cashflows));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

[
  { month: 'jan', value: 10 },
  { month: 'feb', value: '' },
  { month: 'mar', value: 20 },
  { month: 'apr', value: '' }
]