使用 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: '' } ]
廣告