Home > Software design >  array.reduce() but need to set a key for the return value
array.reduce() but need to set a key for the return value

Time:11-11

I have an array where I am using .reduce to group all the matching ids of the array into new array with the id.

The problem is that my output looks like this


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

I need to have the output like this

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

Here is my attempt at the reducer function

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

CodePudding user response:

If there is single object inside array then you can easily achieve using Object.entries()

For demo purposes, I've used "object" as a string

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

May be this is what you're looking for. We have a Array.prototype.reduce() method that returns our desired object array.

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, []))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related