WAG
WAG

Reputation: 23

How can I instantiate a dictionary in Javascript where all keys map to the same value?

I have an array like:

let arr = ['ABC', 'DEF']

And I'd like to transform that array to

let obj = {"ABC": 0, "DEF": 0}

What's the appropriate ES6 syntax to make that transformation?

let arr = ['ABC', 'DEF']
arr.reduce(x => ({[x] : 0 }))

This is close but I end up with {"ABC": 0}

Basically, I want to take an array of arbitrary length and assign all of the values in that array to a "default" value of 0.

Thanks!

Upvotes: 2

Views: 62

Answers (4)

A.RAZIK
A.RAZIK

Reputation: 434

You can just use Array.reduce and pass an empty object as the initial value like code below:

var arr = ["ABC","DEF"].reduce((a,b)=> (a[b]=0,a),{});
console.log(arr);

Upvotes: 0

fro
fro

Reputation: 442

obj = arr.reduce((result, item, index) => {
  result[item] = 0
  return result
}, {})

Hopefully, this will help you. let me know if you have any issues.

Upvotes: 0

Bergi
Bergi

Reputation: 665487

Just use a plain, simple loop:

const arr = ['ABC', 'DEF'];
const obj = {};
for (const x of arr) obj[x] = 0;

If you want to get fancy, I'd recommend Object.fromEntries:

Object.fromEntries(arr.map(x => [x, 0]))

Upvotes: 1

epascarello
epascarello

Reputation: 207557

You are just making single objects like map. You need to keep returning the object.

const arr = ['ABC', 'DEF']
const result = arr.reduce((o, k)  => ({[k] : 0, ...o }), {});
console.log(result)



const result2 = arr.reduce((o, k)  => (o[k] = 0, o), {});
console.log(result2)

Upvotes: 0

Related Questions