4

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'
}
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
unicorn_surprise
  • 951
  • 2
  • 21
  • 40

4 Answers4

11

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);
Tanner Dolby
  • 4,253
  • 3
  • 10
  • 21
1

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'}
LearnerAndLearn
  • 383
  • 4
  • 9
1

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

Andy
  • 61,948
  • 13
  • 68
  • 95
-1
const arr = [{key:"address", value:"123 fake street"},{key:"loan", value:"no"},{key:"property", value:"no"}];
const object = arr.reduce(
  (obj, item) => Object.assign(obj, { [item.key]: item.value }), {});

console.log(object)

One more solution which is 99% faster (jsperf tested)

const object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});

and More simplest solution


// original
const arr = [ 
  {key:"address", value:"123 fake street"},
  {key:"loan", value:"no"},
  {key:"property", value:"no"}
];

//convert
const result = {};
for (var i = 0; i < arr.length; i++) {
  result[arr[i].key] = arr[i].value;
}

console.log(result);

Anik Saha
  • 37
  • 6