Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

242
Views
How can I spread array elements into an object as the keys, and define some value for them?

Let say I have an array:

const arr = ['a',  'b, 'c'];

I want to create an object like this:

{ 'a': true, 'b': true, 'c': true}

How can I do this?

const obj = {...arr: true} 

did not work

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

Yeah, that's not a valid assignment. The first way that comes to mind - if you want one of those cool ES6 one-liners - would be:

const obj = Object.fromEntries(arr.map((el) => [el, true]));
about 4 years ago · Santiago Gelvez Report

0

Using Array#reduce:

const arr = ['a', 'b', 'c'];

const res = arr.reduce((acc, key) => ({ ...acc, [key]: true }), {});

console.log(res);

about 4 years ago · Santiago Gelvez Report

0

Using Object.assign and spread the array (with map).

const arr = ['a', 'b', 'c'];

const res = Object.assign({}, ...arr.map(key => ({[key]: true})));

console.log(res);

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!