Reputation: 17
I need to generate an enumErrorList
like this
Errors={
none:0,
subject:1,
content:2,
sender:4,
recipient:8
}
from an array like this
let errors=[
'none',
'subject',
'content',
'sender',
'recipient'
]
but I’m sorry I’m not very familiar with enum.
Upvotes: 0
Views: 176
Reputation: 29010
You can take the array then use Array#reduce
and Object.assign
to generate an object there where:
let errors=[
'none',
'subject',
'content',
'sender',
'recipient'
]
const Errors = errors.reduce(
(acc, item, index) => Object
.assign(
acc,
{[item]: Math.floor(2 ** (index - 1))}
),
{}
)
console.log(Errors)
Or via bit arithmetic to only produce powers of 2 by setting bit n-1
starting with 0
when n=0
:
let errors=[
'none',
'subject',
'content',
'sender',
'recipient'
]
const Errors = errors.reduce(
(acc, item, index) => Object
.assign(
acc,
{[item]: (1 << index) >> 1}
),
{}
)
console.log(Errors)
Upvotes: 1
Reputation: 1
Use Object.entries and Object.fromEntries as follows
let errors=[
'none',
'subject',
'content',
'sender',
'recipient'
]
let Errors = Object.fromEntries(Object.entries(errors).map(([a,b]) => [b, ((1<<a)>>1)]));
console.log(Errors)
Upvotes: 2