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 } });
CodePudding user response:
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.
CodePudding user response:
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})
)