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?

1
  • There are quite a few dups with quite a few answers, but one of the better ones is here stackoverflow.com/a/48589524/294949 Commented Aug 2, 2022 at 15:51

1 Answer 1

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)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.