1

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
asked Apr 10, 2020 at 14:14

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

answered Apr 10, 2020 at 14:15
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);

answered Apr 10, 2020 at 14:18

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]: {} }), {});
answered Apr 10, 2020 at 14:18

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

answered Apr 10, 2020 at 14:19

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

answered Apr 10, 2020 at 14:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.