-1

What is the best way to convert from this array

[{key: "key1", value: "1"},{key: "key2", value: "2"}]

to

{"key1":"1","key2":"2"}
Sarun UK
  • 6,210
  • 7
  • 23
  • 48
Yudha Pratama
  • 71
  • 1
  • 7

2 Answers2

3

Using Array.prototype.reduce, you can convert it easily as follows.

const input = [{key: "key1", value: "1"},{key: "key2", value: "2"}];
const output = input.reduce((acc, cur) => {
  acc[cur.key] = cur.value;
  return acc;
}, {});
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
1

You can do this with a simple for loop by iterating your array and storing your keys/values in an object:

const input = [{key: "key1", value: "1"},{key: "key2", value: "2"}];
const out = {};
for (const item of input) {
  out[item.key] = item.value;
}
console.log(out);
frodo2975
  • 10,340
  • 3
  • 34
  • 41