-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?

6
  • What have you tried to convert the first data-set into the data structure you want? Commented May 28, 2022 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 Commented May 28, 2022 at 15:45
  • 6
    Object.assign({}, ...array) see: Object.assign() Commented May 28, 2022 at 15:45
  • Solution Here stackoverflow.com/a/43626263/1501286 Commented May 28, 2022 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 Commented May 28, 2022 at 16:01

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

3 Comments

just spread into Object.assign as per my comment, this is a reduce call plus n assign calls, vs 1 assign call.
Yes, that is true, I wished you put this as an answer so more people can access it. It's the cleanest answer to this question.
It's a duplicate, so it was more appropriate to close
0
let obj = {}
for(let i =0; i< arr.length; i++){
  let o = Object.keys(arr[i])
  obj[o[0]] = arr[i][o[0]]
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.