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