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'
}
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);
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'}
Just use a simple for...of loop to iterate over the array, and Object.entries to extract the key/value. Then just update an empty object with that information
const item = [
{ address: '123 fake street' },
{ loan: 'no' },
{ property: 'no' }
];
const obj = {};
for (const el of item) {
const [[key, value]] = Object.entries(el);
obj[key] = value;
}
console.log(obj);
Additional documentation