Kozz
Kozz2y ago

✅ – bfrisco – 14-14 Dec 18

Is there any shorthand way to do this?
const obj = {};
obj['a']['b']['c'] = 'a'
// Cannot read properties of undefined (reading 'b')
const obj = {};
obj['a']['b']['c'] = 'a'
// Cannot read properties of undefined (reading 'b')
Current solution:
const obj = {}
obj['a'] = {}
obj['a']['b'] = {};
obj['a']['b']['c'] = 'a';
const obj = {}
obj['a'] = {}
obj['a']['b'] = {};
obj['a']['b']['c'] = 'a';
5 Replies
EvokeMe
EvokeMe2y ago
const obj = {a: {b: {c: `a`}}}
const obj = {a: {b: {c: `a`}}}
@bfrisco ^^
Kozz
Kozz2y ago
ah, thanks. i'd still want to preserve any other values, but can use optional chaining with destructuring i believe
EvokeMe
EvokeMe2y ago
Also u can use dynamic keys, like this:
const key = `b`
const obj = {a: {[key]: {c: `a`}}}
const key = `b`
const obj = {a: {[key]: {c: `a`}}}
@bfrisco ^^
Kozz
Kozz2y ago
yeah, my actual code is like this now:
stats = {
...stats,
[deviceType]: {
...stats?.[deviceType],
// etc
}
}
stats = {
...stats,
[deviceType]: {
...stats?.[deviceType],
// etc
}
}
I think this will work, TY
reactibot
reactibot2y ago
This question has an answer! Thank you for helping 😄 If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1054038850541981827 This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/565213527673929729/1054038850541981827