1

I am trying to convert array to objects .

let arr = ["value1","value2"]

My trying code is :

 Object.assign({},arr)

expected Output :

  {value1:{},value2:{} }

5 Answers 5

3

You can try with .forEach() as the following:

const arr = ["value1", "value2"];
const result = {};

arr.forEach(e => result[e] = {});

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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

Or: ``` arr.reduce((accumulator, value) => Object.assign(({ [value]: {} }, accumulator)))```
1

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);

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.