Reputation: 1039
Is it possible to set javascript objects dynamically?
I your create objects this way:
let data = {a: {b: 'value'}};
but I need to create it this way:
let data ['a'] ['b'] = 'value';
Object creation will happen within a loop dynamically. That's why I need the second way.
Upvotes: 1
Views: 73
Reputation: 589
You can't in Javascript, because [] operator cannot override in JavaScript.
If you use ruby, you can by following way.
class MyHash < Hash
def [](key)
if has_key? key
super
else
self[key] = self.class.new
end
end
end
my_hash = MyHash.new
my_hash[1][2][3] = "a"
puts my_hash
=> {1=>{2=>{3=>"a"}}}
This can be done by "[]" operator overriding. JavaScript doesn't support "[]" operator overriding.
How would you overload the [] operator in javascript
Then you should
lat data = {}
data[a] = data[a] ? data[a] : {}
data[a][b] = "value"
Upvotes: 2
Reputation: 18662
You need to do
let data = {};
data['a'] = {'b': 'value'}
Upvotes: 1