javascript - 从数组中生成 Angular reducer

标签 javascript angular ecmascript-6 rxjs

据我了解,对于使用 rxjs 计算 Angular 中的数组,我使用reduce,例如,如果我想要 count : [{id: 1, items: [10, 20, 30] }] 我使用以下代码:

const item = from([{id: 1, items: [10, 20, 30]}]);
item.pipe(
  map(actions => actions.items),
  mergeAll(),
  reduce((acc, i) => acc + i, 0)
).subscribe(p => console.log('Print 60: ', p)); 

问题是如何在以下数组中创建一个 reducer :

const items = [
{
  id: 1,
  boxing: [1, 2, 2]
},
{
  id: 2,
  boxing: [10, 10, 20]
}]; 

预期结果:

[{
  id: 1,
  boxing: 5
},
{
  id: 2,
  boxing: 40
}]

我将感谢您的帮助

最佳答案

您可以通过使用 reducemap as 轻松地使用 JavaScript 来完成此操作

const items = [
     {id: 1, boxing: [1, 2, 2]},
     {id: 2, boxing: [10, 10, 20]}
];

let reducedItems = items.map(val => {
  return {
    id: val.id,
    boxing: val.boxing.reduce((a, i) => a + i)
   }
});

console.log(reducedItems);

关于javascript - 从数组中生成 Angular reducer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56436685/

相关文章:

javascript - 参数可以用于创建新的对象键并作为同一函数中的变量吗?

javascript - 按属性对对象数组进行排序

javascript - 如何以编程方式打开时间选择器

javascript - 相当于 jQuery .animate() 的纯 JS

javascript - 在 Angular 2 中创建自定义表单控件

angular - 从嵌套在 Firestore 文档中的集合中获取数据的最佳方法是什么?

Angular (4) : disable the whole form (group) instead of each input separately?

javascript - 如何使用 Meteor 通过动态路径导入

javascript - 使用js箭头函数作为参数

javascript - 嵌套 .then() 函数