Shorthand to declaring empty object properties in Javascript, is there any?

23,302

Solution 1

Wouldn't that work?

Core.registry.taskItemSelected = {
  id: null,
  name: null,
  parent: null,
  ...
};

Solution 2

Something like this should work:

var props = ["id", "name", "parent", ...];
Core.registry.taskItemSelected = {};
for (var i = 0; i < props.length; i++)
   Core.registry.taskItemSelected[props[i]] = "";

Edit: following the OP comments, here is better version with same final result:

Object.prototype.declare = function (varArray) {
    for (var i = 0; i < varArray.length; i++) {
        this[varArray[i]] = {};
    }
};

//usage:
var props = ["id", "name", "parent"];
Core = {};
Core.declare(props);

And live test case as well: http://jsfiddle.net/5fRDc/

Share:
23,302
Edward
Author by

Edward

Updated on August 09, 2022

Comments

  • Edward
    Edward over 1 year

    I need to declare a lot of object properties in my script and I wonder if the're any way to shorten this:

    Core.registry.taskItemSelected;
    Core.registry.taskItemSelected.id;
    Core.registry.taskItemSelected.name;
    Core.registry.taskItemSelected.parent;
    Core.registry.taskItemSelected.summary;
    Core.registry.taskItemSelected.description;
    
  • Edward
    Edward almost 13 years
    Is there any way to leave out the null and go like: Core.registry.taskItemSelected = {id, name, parent...}; Or would this just create a numerated properties with empty values?
  • Edward
    Edward almost 13 years
    Can I just extend the Object object with your function by doing Object.prototype.declare = function ... and have it accept an array like var props = [....]. I might then go like Core.registry.taskItemSelected.declare(props) How would I go about setting the properties in the right object?? Using this
  • Shadow The Kid Wizard
    Shadow The Kid Wizard almost 13 years
    Sorry @Edward but I'm not (yet) familiar with those things.. but feel free to try it and in case it works let me know.
  • Zecc
    Zecc almost 13 years
    @Edward You could, but you may want to check out Object.create and Object.defineProperties instead
  • Edward
    Edward almost 13 years
    @Shadow Wizard All ideas help (Itried it out, it actually works), thanx.
  • Edward
    Edward almost 13 years
    @Zecc Will look into Object.create and Object.defineProperties!
  • Edward
    Edward almost 13 years
    var props = ["id", "name", "parent"]; Object.prototype.declare = function (varArray) { for (var i = 0; i < varArray.length; i++) { this[varArray[i]] = {}; } } Core = {}; Core.declare(props);
  • João Pimentel Ferreira
    João Pimentel Ferreira over 6 years
    Wouldn't be shorter 0 inseatd of null? Because formally you would use undefined
  • Félix Saparelli
    Félix Saparelli over 6 years
    0 might not be "an empty value". Perhaps void 0?