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.

1
  • please! Help-me! Commented Nov 30, 2019 at 6:59

2 Answers 2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I'm glad to help you. Thank you.
1

You need to do

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.