最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cleanest way to convert this array into a single object? - Stack Overflow

programmeradmin7浏览0评论

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'
}

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'
}
Share Improve this question edited Nov 18, 2021 at 21:21 vitaly-t 26k17 gold badges127 silver badges150 bronze badges asked Nov 16, 2021 at 4:33 unicorn_surpriseunicorn_surprise 1,1096 gold badges26 silver badges44 bronze badges 1
  • Check this answer.. stackoverflow./a/67584636/7785337 – Maniraj Murugan Commented Nov 16, 2021 at 4:41
Add a ment  | 

4 Answers 4

Reset to default 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);

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

  • Destructuring assignment
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);

发布评论

评论列表(0)

  1. 暂无评论