Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested object assignment in Node.js

Suppose I have an object (baz) of variable contents. How can I assign a sub-object (foo) with a key (baz) to that object in one line?


Examples:

var baz = {}
baz.foo.bar = 1;
console.assert(baz === { foo: { bar: 1 } });

(or, in the case where foo is already defined)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var baz = { foo: { 1: "b" } };
baz.foo.bar = 1;
console.assert(baz === { foo: { 1: "b", bar: 2 } });

>Solution :

It’s possible to put all in one line, though personally I wouldn’t recommend it. You’re technically doing two pretty different things:

  • Assign an object as a property if the object doesn’t exist yet
  • Assign a property if the object already exists, mutating the existing object

You can assign baz.foo or the empty object to baz.foo, then assign the bar property value to the resulting object:

const baz = {};
(baz.foo ??= {}).bar = 1;
console.log(baz.foo.bar);

const baz2 = {};
(baz2.foo ??= {}).bar = 1;
console.log(baz2.foo.bar);

I’d prefer

// Create the object if it doesn't exist yet
baz.foo ??= {};
// Assign the new nested value
baz.foo.bar = 1;

Code readability is more important than golfing in most cases.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading