I am trying to convert array to objects .
let arr = ["value1","value2"]
My trying code is :
Object.assign({},arr)
expected Output :
{value1:{},value2:{} }
norbitrial
15.2k10 gold badges39 silver badges66 bronze badges
5 Answers 5
You can try with .forEach() as the following:
const arr = ["value1", "value2"];
const result = {};
arr.forEach(e => result[e] = {});
console.log(result);
answered Apr 10, 2020 at 14:15
norbitrial
15.2k10 gold badges39 silver badges66 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You could take Object.fromEntries and map the wanted keys with empty objects.
let keys = ["value1", "value2"],
object = Object.fromEntries(keys.map(key => [key, {}]));
console.log(object);
answered Apr 10, 2020 at 14:18
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Comments
Use array reduce!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
arr.reduce((accumulator, value) => ({ ...accumulator, [value]: {} }), {});
1 Comment
TVG
Or: ``` arr.reduce((accumulator, value) => Object.assign(({ [value]: {} }, accumulator)))```
You can use .reduce() to get the desired output:
const data = ["value1", "value2"];
const result = data.reduce((r, k) => (r[k] = {}, r), {});
console.log(result);
answered Apr 10, 2020 at 14:19
Mohammad Usman
39.5k20 gold badges99 silver badges101 bronze badges
Comments
There's also Object.fromEntries method specifically designed to convert an array of entries (key-value tuples) to an Object.
let arr = ['value1', 'value2'];
let entries = arr.map(el => [el, {}]);
let obj = Object.fromEntries(entries);
console.log(obj);
answered Apr 10, 2020 at 14:19
junvar
11.7k2 gold badges35 silver badges52 bronze badges
Comments
lang-js