-1

Can you please help me to create object out of array of objects?

Array to convert arr = [{name:'Ryan'}, {surname:'raynold'}]

required output finalObj = {name:ryan, surname:raynold}

I tried to get the result by doing

let objectArr = Object.assign({}, arr);

but result was like this

{ 0: {shoulder: "14"}, 1:{neck: ""} }

sevack
  • 13
  • 3

2 Answers2

2

This is a good case for Object.assign.

let arr = [{name:'Ryan'}, {surname:'raynold'}]

let finalObj = Object.assign({}, ...arr);

console.log(finalObj);

Object.assign can take multiple objects as arguments, and so you can spread those objects from your input array. The first argument represents the object in which the others are merged.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Nice one!!! This really is a good case for Object.assign! – Lazar Nikolic Sep 08 '20 at 11:22
  • Thanks a lot, I wasn't spreading the arr thats why i wasn't getting the required result. – sevack Sep 08 '20 at 11:25
  • What if the second object has nested object ? let arr = [ { name:'Ryan' } , { surname: {middleName: 'Robins' }, {lastName: 'Raynolds' } } ] how do i get an object of { name: 'Ryan' , middleName: 'Robins' , lastName: 'Raynolds' } – sevack Sep 08 '20 at 12:05
  • Then you must pick up the entries at the nested level (loop over them). If you cannot make it work, and cannot find a similar question, then feel free to ask a new question. – trincot Sep 08 '20 at 16:01
0

You could do it with a array reduce like this:

let finalObj = arr.reduce((acc, cur) => ({...acc, ...cur}), {})
Jeremias
  • 343
  • 1
  • 3
  • 9