0

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 } });
3
  • Noting here that yes, I can easily write a function where I can use nestedAssign(baz, "foo", "bar", 2), but I am looking for a built-in solution. Commented Dec 27, 2021 at 0:26
  • Did you mean, key bar? Commented Dec 27, 2021 at 0:28
  • It isn't entirely clear to me what you're trying to do and why. Are you looking for Object.assign()? Some sort of spread operator? Commented Dec 27, 2021 at 0:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Valid point, I was looking to do it in 1 line to make it more readable while less verbose. This seems to work just as well, much better than writing an existing function to do this.
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})

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.