Merging objects in JavaScript
Lately I need to get my hand dirty in JavaScript much more than even before. Sometimes I feel so confused and lost that it reminds me my first steps in programming many years ago. Sometimes I try to to smuggle some Ruby idioms and many times it is no the best approach.
Couple days ago I had a problem with transforming list of keys into
object, hash with values set to true
for all keys. From ['a', 'b']
I had to do { a: true, b: true}
. Man! In Ruby it would be a
no-thinker for me, but in JavaScript it was not so easy.
[:a, :b:, :c].inject({}) { |hash, key| m.merge(key => true) }
What is equivalent of Hash#merge in JavaScript?
That question strike my mind immediately. I know how reduce
function
works and love it in any language. So my first approach was like:
['a', 'b', 'c'].reduce((acc, name) => Object.assign(acc, { name: true }), {});
As you probably know it didn’t work as I imagine. I ended up with
object { name: true }
. But there is a way to do it better. In Ruby
and JavaScript accessing to object/hash properties works the same way using []
.
['a', 'b', 'c'].reduce((acc, name) => Object.assign(acc, { [name]: true }), {});
There is also new sexy thing in JavaScript - spread operator which I really like from the first time I saw it.
['a', 'b', 'c'].reduce((acc, name) => { return { ...acc, [name]: true } }, {});
It is hard to judge for me which solution is better. ...
looks very
dandy, but accumulation of (
, {
, ...
, }
, )
chars in this
line is to big for me … and there is also this return
somewhere is the
middle. Couple more weeks with JavaScript and probably I will used to
this.