1

What's the easiest way to make nested objects in TypeScript? I want to be able to add elements in nested objects like this:

let dictionary: { [key: string]: { [key: string]: number  }  } = {};
dictionary['x']['y'] = 2
dictionary['x']['z'] = 5

I expect:

console.log(dictionary['x'])  // -> {'y': 2,'z': 5}

console.log(dictionary['x']['y'])  // -> 2
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
park3r
  • 13
  • 3
  • 1
    Start with `dictionary['x'] = {}`? Unless you use e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy the inner objects won't magically appear. – jonrsharpe Oct 26 '22 at 16:14
  • 1
    Related: [JavaScript: Write to dictionary if key doesn't exist](https://stackoverflow.com/q/67107996) – VLAZ Oct 26 '22 at 16:16
  • Yeah, this looks like a duplicate of that one to me. Note that you could always write `(dictionary.x??={}).y = 2` as a one-liner, if you must – jcalz Oct 26 '22 at 16:28

1 Answers1

1

What's happening is that you are assigning the value 2 to the object at dictionary['x'], which resolves to undefined.

Try to initialise dictionary['x'] = {} first.

toanphan19
  • 88
  • 7