0

I have an object that looks like this:

let myObj = {
  one: 1,
  two: 2,
  three: {
   something: '1'
  }
}

Now, I have a string such as this:

"three.myNestedNewKey"

And I want to add the key myNestedNewKey to the three key, and add a value, let's say the number 2. so that it ends up like this:

let myObj = {
  one: 1,
  two: 2,
  three: {
   something: '1',
   myNestedNewKey: '2'
  }
}

I tried doing this:

myObj["three.myNestedNewKey"] = 2

But it just adds one key like this:

let myObj = {
  one: 1,
  two: 2,
  three: {
   something: '1',
  },
  three.myNestedNewKey: 2,
}

So it adds just one new key with the dot in it.

I do want to keep the existing values of what is inside the three key, but add myNestedNewKey to it.

Any ideas how to do this in a simple way?

  • There are quite a few dups with quite a few answers, but one of the better ones is here https://stackoverflow.com/a/48589524/294949 – danh Aug 02 '22 at 15:51

1 Answers1

0

You can reference three after myObj then use the brackets

let myObj = {
  one: 1,
  two: 2,
  three: {
   something: '1'
  }
}

myObj.three["myNestedNewKey"] = 2
console.log(myObj)
imvain2
  • 15,480
  • 1
  • 16
  • 21