简体   繁体   中英

How to create javascript objects dynamically?

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.

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"

You need to do

let data = {};
data['a'] = {'b': 'value'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM