-2

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?

Emeka Orji
  • 174
  • 4
  • 11
  • What have you tried to convert the first data-set into the data structure you want? – Michael May 28 '22 at 15:44
  • @VLAZ, Changed that now, I do have an array but used a function to turn it to an object, so I just thought to post the object directly. Thanks – Emeka Orji May 28 '22 at 15:45
  • 6
    `Object.assign({}, ...array)` see: [Object.assign()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) – pilchard May 28 '22 at 15:45
  • Solution Here https://stackoverflow.com/a/43626263/1501286 – salsan May 28 '22 at 15:56
  • Yh, just checked it, found my answer already. Plus @pilchard answer here in the comments was the most reasonable and cleanest of them – Emeka Orji May 28 '22 at 16:01
  • `const newObj = origObj.reduce((acc, el) => ({...acc,...el}), {})` – shivangg May 28 '22 at 16:02

2 Answers2

3

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);
Alexey Zelenin
  • 710
  • 4
  • 10
0
let obj = {}
for(let i =0; i< arr.length; i++){
  let o = Object.keys(arr[i])
  obj[o[0]] = arr[i][o[0]]
}
Anuj Verma
  • 2,519
  • 3
  • 17
  • 23