[Solved] How to dynamically create an object when looping an array?


I would use reduce function for that.

The agg is an aggregator which aggregate our final result.

The item is representing each element in the array.

const arr= [
  {key: 'a', value: '1'},
  {key: 'b', value: '2'},
  {key: 'c', value: '3'},
];

const result = arr.reduce((agg, item) => {
  agg[item.key] = item.value
  return agg
}, {})
console.log(result)
// { a: '1', b: '2', c: '3' }

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

2

solved How to dynamically create an object when looping an array?