使用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: '' }
]热门推荐
10 入学祝福语简短走心
11 出阁祝福语简短句子
12 六一婚礼文案祝福语简短
13 祝福语大全简短6个
14 师姐毕业送花祝福语简短
15 九子订婚祝福语简短
16 初六开工祝福语简短
17 舅妈生日红包祝福语简短
18 国庆中秋祝福语简短搞笑