array.reduce() 但需要为 return 值设置一个键

array.reduce() but need to set a key for the return value

我有一个数组,我在其中使用 .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] ]}
  
]

这是我对reducer功能的尝试

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({}));

如果数组中只有一个对象,那么你可以使用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);

也许这就是您要找的。我们有一个 Array.prototype.reduce() 方法 returns 我们想要的对象数组。

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, []))