代码之家  ›  专栏  ›  技术社区  ›  tb517

.map()不是reduce()中的函数

  •  0
  • tb517  · 技术社区  · 5 年前

    我有以下代码:

    map(res => {
        const finalRows = res.reduce((acc, curr) => {
          return [
            ...acc,
            ...curr.map(row => ({
              ...row,
              chevron: ' ',
            }))
          ]
        }, []);
    .....

    “res”看起来像一个对象数组,这些对象是行。使用reduce(),它应该返回一个数组,但我使用map遍历当前的每一行并添加一个“chevron”列。我觉得可能它还不知道它返回了一个数组,还把它当作一个对象对待,所以我得到了错误的答案当前地图不是一个函数,但是,我不确定这是否是真正的问题。有什么想法吗?

    0 回复  |  直到 5 年前
        1
  •  0
  •   ClementNerma    5 年前

    让我们更深入地了解一下您的代码:

    • 如你所说, res 是一个对象数组
    • 第二个论点 .reduce 的回调是所提供数组中的当前项
    • 所以呢 curr 是一项 物件

    但在这里,似乎 货币 不是数组,而是另一种类型的对象(如JSON),这就是为什么会出现此错误。

    只有在 物件 曾经是一个数组,就像 .map 不能在非数组对象上调用。

    另外,以更简单的方式编写代码的另一种方法是:

    // For each row of the `res` array...
    res.map(row => {
      // Clone it, so the new row isn't linked to the existing one
      const newRow = row.slice(0);
      // Set its 'chevron' property
      newRow.chevron = ' ';
      // Return the new row
      return newRow;
    }); // Here we get the new array of objects