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/
Author by
Edward
Updated on August 09, 2022Comments
-
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 almost 13 yearsIs 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 almost 13 yearsCan 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 almost 13 yearsSorry @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 almost 13 years@Edward You could, but you may want to check out Object.create and Object.defineProperties instead
-
Edward almost 13 years@Shadow Wizard All ideas help (Itried it out, it actually works), thanx.
-
Edward almost 13 years@Zecc Will look into Object.create and Object.defineProperties!
-
Edward almost 13 yearsvar 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 over 6 yearsWouldn't be shorter
0
inseatd ofnull
? Because formally you would useundefined
-
Félix Saparelli over 6 years
0
might not be "an empty value". Perhapsvoid 0
?