Javascript, Create Objects and manage attributes.

When you have to create objects the syntax is :

var my_object = {};

to add attributes you can do :

var my_object = {
  attribute_one : 'value_1',
  attribute_twe : 'value_2',
  ...
}

or

var my_object = {};
my_object.attribute1 = 'value_1';
my_object.attribute2 = 'value_2';
etc ..

Now if you need to get all the attributes from the object :

for(var i in my_object)
{
   console.log( 'attribute ' + i + ' has value ' + my_object[i]);
}

Assuming that you have an existent object and you need to merge attributes from another one :

var attributes = {
  height : 10,
  width : 20
};

var config = {a : 1, b : 2 , c : 3};

for (var i in attributes){
  eval('config.' + i + ' = ' + attributes[i] + ';\n');
}
console.log(config);

One thought on “Javascript, Create Objects and manage attributes.

Leave a Reply