js object set property code example
Example 1: js defineProperty
var obj = {};
var descriptor = Object.create(null);
descriptor.value = 'static';
Object.defineProperty(obj, 'key', descriptor);
Object.defineProperty(obj, 'key', {
enumerable: false,
configurable: false,
writable: false,
value: 'static'
});
function withValue(value) {
var d = withValue.d || (
withValue.d = {
enumerable: false,
writable: false,
configurable: false,
value: value
}
);
if (d.value !== value) d.value = value;
return d;
}
Object.defineProperty(obj, 'key', withValue('static'));
(Object.freeze || Object)(Object.prototype);
Example 2: add property to object javascript
let yourObject = {};
let yourKeyVariable = "yourKey";
yourObject[yourKeyVariable] = "yourValue";
yourObject["yourKey"] = "yourValue";
yourObject.yourKey = "yourValue";
Example 3: add property with value in js
var myObject = {
sProp: 'some string value',
numProp: 2,
bProp: false
};