-1

I want to create JSON object using pure JavaScript as below:

{
  "0": {
     "0": {
          "key1": 1,
          "key2": 2
     },
     "1": {
          "key1": 1,
          "key2": 2
      }
  }
  "1": {
     "0": {
          "key1": 1,
          "key2": 2
      }
  }
}

But when I try below code I get error for undefined:

var myJosnObj = {};
myJosnObj["0"]["0"] = {"key1": 1,"key2": 2};

I am getting error: Error: myJosnObj[0] is undefined

I want to either create or update the existing key in the json document.

User7723337
  • 11,857
  • 27
  • 101
  • 182
  • Firstly, `myJosnObj["0"]` tries to grab the value at the key `"0"` in your `myJosnObj` (which doesn't exist, so you get `undefined`), and then the subsequent `["0"]` tries to set the key `"0"` on that value you just grabbed to the object to the right of the `=`. Since that value you grabbed doesn't exist/is undefined, so can't set the `"0"` key on it – Nick Parsons Apr 21 '21 at 11:44

2 Answers2

2
const myJosnObj = {};
myJosnObj["0"] = {}
myJosnObj["0"]["0"] = {"key1": 1,"key2": 2};

You need to define myJosnObj["0"]

Vulwsztyn
  • 2,140
  • 1
  • 12
  • 20
1

you can directly do :

const myJosnObj = 
      { "0": 
        { "0": { "key1": 1, "key2": 2} 
        , "1": { "key1": 1, "key2": 2} 
        } 
      , "1": 
        { "0": { "key1": 1, "key2": 2} 
        } 
      } 
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40