1

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.

randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72
Jobsdev
  • 1,047
  • 3
  • 11
  • 28

2 Answers2

2

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"
久保圭司
  • 579
  • 5
  • 16
  • 1
    thank you my friend! I was able to solve my problem with your theoretical explanation. I was unaware that it is not possible to change the operator of a variable in javascript. Given this, I created the object type variable {} (which is already the right type) and managed to solve my problem. Thank you very much. – Jobsdev Nov 30 '19 at 08:07
  • I'm glad to help you. Thank you. – 久保圭司 Nov 30 '19 at 09:18
1

You need to do

let data = {};
data['a'] = {'b': 'value'}
randominstanceOfLivingThing
  • 16,873
  • 13
  • 49
  • 72