What is the best way to convert from this array
[{key: "key1", value: "1"},{key: "key2", value: "2"}]
to
{"key1":"1","key2":"2"}
What is the best way to convert from this array
[{key: "key1", value: "1"},{key: "key2", value: "2"}]
to
{"key1":"1","key2":"2"}
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);
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);