2

Can't figure out how to set multiple object elements at a time?

For example, how to write

myobject.field1 = 12;
myobject.field2 = 13;
myobject.field3 = 14;
myobject.field4 = 15;
myobject.field5 = 16;    
myobject.field6 = 17;

without writing myobject. multiple times? Somehow with comma syntax?

Dims
  • 47,675
  • 117
  • 331
  • 600
  • Javascript has `with`. Look at this answer: http://stackoverflow.com/questions/61088/hidden-features-of-javascript#61118 – Logan Serman Dec 26 '11 at 12:10
  • 1
    JavaScript also got `with` keyword. It's [not good practice](http://stackoverflow.com/questions/61552/are-there-legitimate-uses-for-javascripts-with-statement) to use it though. – Shadow The GPT Wizard Dec 26 '11 at 12:10

2 Answers2

3

JavaScript does have a with, but its use is not recommended, mainly because it can clobber variables outside of what with is supposed to work on (if the property does not exist).

You could turn those assignments into a loop...

for (var i = 0; i < 7; i++) {
    myobject['field' + i] = 11 + i;
}
alex
  • 479,566
  • 201
  • 878
  • 984
  • Ahh, just because I like to rant about `with` not being good practice and because I'd link the exact same post by Chuck No... ehem Doug Crockford. – Camilo Martin Dec 31 '11 at 02:40
1

If your object only contains fields you can declare it like this:

var myobject = {
    field1: 12,
    field2: 13,
    field3: 14,
    field4: 15,
    field5: 16,
    field6: 17
};

If you use jQuery and your object has other functions and properties you can do this:

$.extend(myobject, {
    field1: 12,
    field2: 13,
    field3: 14,
    field4: 15,
    field5: 16,
    field6: 17
});
Camilo Martin
  • 37,236
  • 20
  • 111
  • 154
Luis Perez
  • 27,650
  • 10
  • 79
  • 80
  • 4
    Those equal signs inside the { .. } should be colons and drop the last comma in each group. – HBP Dec 26 '11 at 14:14