Chris
Chris

Reputation: 1428

Dynamically create an object as needed without if checks

So I thought I was crazy, and I may be but this seems pretty simple. Say I have this bit of code:

let a = {};
a.b.c.d.e.f.g = 'Something Awesome';

Now you can imagine the if-check nightmare that would have to take place to see if each level exists. And even if I had a fancy looping way to do it, someone else has had to think this up.

I think CoffeeScript had something like this, but I can't seem to find anything on it. I was also wondering if there was an ECMAScript6 or lodash way of doing the same type of thing?

Maybe something like:

set(a, b, c, d, e, f, g, 'Something Awesome');

And in that case even:

set(a, b, c, d, {e: {f: {g: 'Something Awesome'}}});

But the last option would wipe out anything that may exist in e, f, and g.

Upvotes: 0

Views: 50

Answers (1)

Ori Drori
Ori Drori

Reputation: 192016

You are referring to lodash's _.set():

const a = {};
_.set(a, 'b.c.d.e.f.g', 'Something Awesome');

console.log(a);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Upvotes: 1

Related Questions