javascriptarraysobjectkey-value

How to spread Objects inside Array in JavaScript


I have this array

[
  {FirstName: 'Emeka'},
  {MiddleName: 'Praise'},
  {LastName: 'Orji'},
  {Date: 'Today'},
  {Month: 'July'},
  {Year: '2022'},
  {Gender: 'Female'},
  {MaritalStatus: 'married'},
  {State: 'Lagos'},
  {Origin: 'Ape'},
]

I want to turn it into an object

{
  FirstName: 'Emeka',
  MiddleName: 'Praise',
  LastName: 'Orji',
  Date: 'Today',
  Month: 'July',
  Year: '2022',
  Gender: 'Female',
  MaritalStatus: 'married',
  State: 'Lagos',
  Origin: 'Ape',
}

I have been on this for a long time Pls how can I do this?


Solution

  • const src = [
      {FirstName: 'Emeka'},
      {MiddleName: 'Praise'},
      {LastName: 'Orji'},
      {Date: 'Today'},
      {Month: 'July'},
      {Year: '2022'},
      {Gender: 'Female'},
      {MaritalStatus: 'married'},
      {State: 'Lagos'},
      {Origin: 'Ape'},
    ];
    
    const result = src.reduce((collector, item) => {
      Object.assign(collector, item);
      return collector;
    }, {});
    
    console.log(result);