1

I would like to convert an array that looks like this:

['foo', 'bar', 'baz']

to an object that looks like this:

{
  foo: true,
  bar: true,
  baz: true,
}

In most languages you would have some form of fill(keys, value) function:

var array = ['foo', 'bar', 'baz'];
var object = fill(array, true);
// object = { foo: true, bar: true, baz: true}

But in JS I can only find one for numeric keys using a range, not a list of keys. Is there a fill function that will do exactly that?

3
  • 3
    No but there's .reduce(). (I'm not so sure there's such a .fill() method in "most" languages.) Commented May 23, 2022 at 14:35
  • 4
    Object.fromEntries(array.map(x => [x,true])) Commented May 23, 2022 at 14:37
  • ['foo', 'bar', 'baz'].reduce((a, v) => ({ ...a, [v]: true}), {}) Commented May 23, 2022 at 14:50

5 Answers 5

5

Try this:

const data = ['foo', 'bar', 'baz']
const asObject = Object.fromEntries(data.map(d => ([d, true])))

console.log(asObject)
Sign up to request clarification or add additional context in comments.

Comments

2

You can build an object with .reduce():

var object = array.reduce((o, e) => (o[e] = true, o), {});

edit — or the clever Object.fromEntries() solution mentioned in a comment.

Comments

1

You can map the array values to entries (key, value pairs) and then transform the matrix into an object.

const
  arr = ['foo', 'bar', 'baz'],
  obj = Object.fromEntries(arr.map(v => [v, true]));

console.log(obj);

Comments

1

There isn't such function as fill(keys, value) that you mentioned, but you could also do so:

let tab = ['foo', 'bar', 'baz'];

let obj = {}

tab.forEach(v=>{obj[v]=true});

console.log(obj)

Comments

0

You can create a new object, loop over the array and add each value to it.

let arr = ['foo','bar','baz'];
let obj={};
arr.forEach(el => {obj[el] = true})

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

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.