0

Say you have this object:

myObj = { foo: { bar : 123, baz: 456 } };

To edit the value of bar you can do this:

myObj['foo']['bar'] = 789

But what if you have a method somewhere that changes specific object properties like this:

myObj[key] = value

If you need to use that and you want to edit bar in the myObj object, is it possible with that code?

I tried:

myObj["foo"."bar"] = 789;
myObj["foo"["bar"]] = 789;

But it doesn't work. Is it possible at all to do?

Sometip
  • 332
  • 1
  • 10

1 Answers1

0

Pure JavaScript doesn't allow you to access nested properties with a simple string.

An alterative can be i.e. lodash:

_.get(myObj, 'foo.bar'); // 123

_.set(myObj, 'foo.bar', 789);
hsz
  • 148,279
  • 62
  • 259
  • 315