-1

There is an array which its items should be the keys of an object. As an example:

['key1', 'key2', 'key3']

is my array. I need to have it like this object:

{
  'key1': '',
  'key2': '',
  'key3': ''
}

As it might be so items in array prefer not to use loops. How can create object without loops?

Atousa Darabi
  • 847
  • 1
  • 7
  • 26
  • By "without loops", do you mean "without `for` loops" or "without any kind of looping through an array"? – georg Jun 02 '21 at 15:12
  • Any kind of loops. Not for , while, ... . It takes time to do it. – Atousa Darabi Jun 02 '21 at 15:13
  • 3
    That's not possible. There's no built-in function in javascript like python's `dict.fromkeys`. Your best bet would be `Object.fromEntries(keys.map(k => [k, '']))`, but that's a loop too. – georg Jun 02 '21 at 15:16
  • 1
    ```obj = { [arr[0]]: "", [arr[1]]: "", [arr[2]]: "", };``` That's it. – ikhvjs Jun 02 '21 at 15:18
  • Does this answer your question? [Create an object from an array of keys and an array of values](/q/39127989/90527) – outis Sep 01 '22 at 07:57

2 Answers2

0

This is also a loop, but at least it is a one-liner:

const res=['key1', 'key2', 'key3'].reduce((a,c)=>(a[c]='',a),{});

console.log(res)
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
-1

I don't know why you're against using a loop. If you require the object to be created dynamically you won't really get away with not using a loop of some kind.

This solution technically doesn't directly use a loop ... but it's a silly solution and I don't recommend it.

const keys = ['key1', 'key2', 'key3'];
const res = Object.fromEntries(
  JSON.parse(
    JSON.stringify(keys).replace(/"([^"]+)"/g,'["$1",""]')
  )
);
console.log(res);
Kyle
  • 3,935
  • 2
  • 30
  • 44
  • isn't the ```replace``` method loop through the string as well? – ikhvjs Jun 02 '21 at 16:23
  • @ikhvjs depends on your definition of a loop. Internally, yeah, there’s a loop. But in the code itself there is no actual loop. – Kyle Jun 02 '21 at 22:06