JavaJavaScript
JavaJavaScript

Reputation: 25

How Can I make this javascript code cleaner? Reuse variables

I am fairly new to Javascript.I have to count some values and my current vairable looks like this :

  var mainObj : {  
   "main1":{  
      "var1":0,
      "var2":0,
      "var3":0
   },
   "main2":{  
      "var1":0,
      "var2":0,
      "var3":0
   },
   "main3":{  
      "var1":0,
      "var2":0,
      "var3":0
   }
}

Is there a way i can reuse a single object for all that? Something like :

var mainObj :{  
   "main1":{  
      someOBjInstance
   },
,
   "main2":{  
      someOBjInstance
   }   "main3":{  
      someOBjInstance
   }
   }

Upvotes: 0

Views: 53

Answers (1)

caiohamamura
caiohamamura

Reputation: 2728

It is just a matter of creating copies of the object:

var subObject = {
    "var1":0,
    "var2":0,
    "var3":0
};

var mainObj = { 
    "main1": subObject,
    "main2": Object.create(subObject),
    "main3": Object.create(subObject)
};

If the values are just a bunch of numbers which you want to increment, then you could use arrays instead of Object, which will be faster and easier to manipulate:

var mainArray = [[0,0,0],[0,0,0],[0,0,0]]

Upvotes: 1

Related Questions