使用 JavaScript 进行数据操作

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 8:44:17

假设我们有两个数组描述一些现金流,例如 −

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

相关文章


有用资源