【问题标题】:array.reduce() but need to set a key for the return valuearray.reduce() 但需要为返回值设置一个键
【发布时间】:2021-12-23 15:20:20
【问题描述】:

我有一个数组,我使用 .reduce 将数组的所有匹配 id 分组到具有 id 的新数组中。

问题是我的输出看起来像这样


[
  {
    CHb5591f5db2a546d3af: [ [Object], [Object] ],
    CH5e86016c8b894d9d87: [ [Object], [Object], [Object], [Object], [Object], [Object] ]
  }
]

我需要这样的输出

[
  
    {id: CHb5591f5db2a546d3af, content: [ [Object], [Object] ]},
    {id: CH5e86016c8b894d9d87, content: [ [Object], [Object], [Object], [Object], [Object], [Object] ]}
  
]

这是我对减速器功能的尝试

result = await response.reduce(function (a, i) {
        a[i.messagesId] = a[i.messagesId] || []; //it generates a new property i.messagesId with an array if it does not exist (the value of not existing properties is undefined). if exist, it assign itself 
        a[i.messagesId].push(i);
        return a;
    }, Object.create({}));

【问题讨论】:

    标签: javascript node.js reduce


    【解决方案1】:

    如果数组中有单个对象,那么您可以使用Object.entries()轻松实现

    出于演示目的,我使用"object" 作为字符串

    const arr = [
      {
        CHb5591f5db2a546d3af: [["Object"], ["Object"]],
        CH5e86016c8b894d9d87: [
          ["Object"],
          ["Object"],
          ["Object"],
          ["Object"],
          ["Object"],
          ["Object"],
        ],
      },
    ];
    
    const result = Object.entries(arr[0]).map(([id, content]) => ({ id, content }));
    console.log(result);

    【讨论】:

    • 这对我有用,我会在 Object.entries 上做一些阅读。一旦允许,我会将其标记为答案
    【解决方案2】:

    可能这就是您正在寻找的。我们有一个Array.prototype.reduce() 方法,它返回我们想要的对象数组。

    const array = [
          {
            'CHb5591f5db2a546d3af':
              [
                { animal: 'Cat', name: 'Tom' },
                { animal: 'Dog', name: 'Bruno' }
              ]
          },
          {
            'CH5e86016c8b894d9d87':
              [
                { animal: 'Alligator', name: 'Mike' }
              ]
          },
          {
            'CH5e86016c8b894d9d97':
              undefined
          }
        ]
    
        const reducer = function (acc, item) {
          for (const _key in item) {
            acc.push({
              'id': _key,
              'content': item[_key]
            })
          }
          return acc;
        }
        console.log(array.reduce(reducer, []))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-16
      • 2021-10-18
      • 2019-06-14
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多