Search code examples
javascriptpropertiesobject-literal

Can one set multiple properties inside an object literal to the same value?


For example, can I do this?:

{ 
   a: b: c: d: 1,
   e: 2,
   geh: function() { alert("Hi!") }
}

EDIT: Is there some way I can avoid doing this?:

{ 
   a: 1,
   b: 1,
   c: 1,
   d: 1,
   e: 2,
   geh: function() { alert("Hi!") }
}

Solution

  • You could set a line of equality between various properties:

    var foo = {};
    foo.a = foo.b = foo.c = "Hello";
    

    Or you could just create a method that does the mass-assignment for you:

    var foo = {
        setValue: function( props, value ) {
            while ( props.length ) this[ props.pop() ] = value;
        }
    }
    
    foo.setValue( [ "a", "b", "c" ] , "Foo" );