Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
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)

var baz = { foo: { 1: "b" } };
baz.foo.bar = 1;
console.assert(baz === { foo: { 1: "b", bar: 2 } });
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

For the first case :

baz.foo = {bar :1}

And your code works for the second case

(Note that the following code outputs false :

a = {b:1}
console.log(a==={b:1})

)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!