Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to convert this array into a single object?

Tags:

javascript

Just looking for the cleanest way to turn the following array into the following object format. Thanks a lot

const item = [
  { address: '123 fake street' },
  { loan: 'no' },
  { property: 'no' }
]

const obj = {
    address: '123 fake street',
    loan: 'no',
    property: 'no'
}
like image 683
unicorn_surprise Avatar asked Dec 13 '22 06:12

unicorn_surprise


2 Answers

You can use Object.assign() and spread syntax to convert the array of objects into a single object.

const item = [
  { address: '123 fake street' },
  { loan: 'no' },
  { property: 'no' }
]

const obj = Object.assign({}, ...item);
console.log(obj);
like image 50
Tanner Dolby Avatar answered Feb 11 '23 09:02

Tanner Dolby


Reduce and spread syntax would be one clean way to convert the array to an object.

const item = [
  { address: '123 fake street' },
  { loan: 'no' },
  { property: 'no' }
]

let obj = item.reduce((pre, cur)=>{
    return {...pre, ...cur};
}, {});
    
// Result: obj={address: '123 fake street', loan: 'no', property: 'no'}
like image 22
LearnerAndLearn Avatar answered Feb 11 '23 08:02

LearnerAndLearn