【问题标题】:Using variable within reduce function在 reduce 函数中使用变量
【发布时间】:2019-10-23 18:36:04
【问题描述】:

感觉我在这里遗漏了一些明显的东西。我正在使用这样的reduce函数

const obj = this.data.reduce((ac,{Category, Count}) => (ac[Category] = Count,ac),{});

但是,我现在需要使用变量来动态分类和计数。因此,我已经完成了

const cat = this.format.header[0];
const count = this.format.header[1];
const obj = this.data.reduce((ac,{cat, count}) => (ac[cat] = count,ac),{});

这似乎并没有使用我的变量。我也尝试在其中使用它,但这也不起作用。

如何在 reduce 中使用这些变量?

谢谢

【问题讨论】:

  • 你有一些数据和想要的结果吗?
  • 不是 100% 清楚你在问什么,但你不能通过解构来做到这一点。您必须明确提取属性。
  • 什么是thisthis.data?另外,为什么不直接使用带花括号的箭头函数,然后在其中定义变量呢?
  • 对不起,this.data 是一个数组。这是 VueJS 中的一个组件,我通过 props 传递东西
  • 您不能解构这些变量,但可以将它们作为键传递给您的对象

标签: javascript reduce


【解决方案1】:

您不能使用这种解构方式来实现您想要的:

this.data.reduce((ac,{cat, count}) => (ac[cat] = count,ac),{});

这将尝试从属于数组的对象访问属性catcount,而不是保存变量的对象。但是,您可以这样做:

const cat = this.format.header[0];
const count = this.format.header[1];
const obj = this.data.reduce((ac, o) => (ac[o[cat]] = o[count], ac), {});

【讨论】:

    【解决方案2】:

    reduce() 回调中的catcount 变量将引用每个对象上的属性catcount 是对象数组this.data

    如果您想使用变量解构属性。然后使用以下语法

    [propName]:newName
    

    这是您的代码。

    const cat = this.format.header[0];
    const count = this.format.header[1];
    const obj = this.data.reduce((ac,{[cat]:cat, [count]:count}) => (ac[cat] = count,ac),{});
    

    【讨论】:

      猜你喜欢
      • 2011-11-08
      • 1970-01-01
      • 2023-03-29
      • 2021-07-17
      • 2020-03-26
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多