-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?

5
  • By "without loops", do you mean "without for loops" or "without any kind of looping through an array"? Commented Jun 2, 2021 at 15:12
  • Any kind of loops. Not for , while, ... . It takes time to do it. Commented Jun 2, 2021 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. Commented Jun 2, 2021 at 15:16
  • 1
    obj = { [arr[0]]: "", [arr[1]]: "", [arr[2]]: "", }; That's it. Commented Jun 2, 2021 at 15:18
  • Does this answer your question? Create an object from an array of keys and an array of values Commented Sep 1, 2022 at 7:57

2 Answers 2

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)

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

1 Comment

However it is a loop though, but worked better than others.
-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);

2 Comments

isn't the replace method loop through the string as well?
@ikhvjs depends on your definition of a loop. Internally, yeah, there’s a loop. But in the code itself there is no actual loop.

Your Answer

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.