Say I have an object like:
const myObj = { color: 'red', score: 8 };
I can access these attributes with:
myObj.color // 'red'
and:
Object.values(myObj) // ['red', 8]
I want to be able to store extra data in the object, that is accessible, but won't be found by Object.values()
for example:
myObj.greeting // "hello"
// or alternatively
myObj.greeting() // "hello"
Object.values(myObj // ['red', 8] greeting is not picked up by Object.values()
Preferably using modern JavaScript like classes if necessary, rather than directly using prototypes.
You can use Object.defineProperty
that set enumerable: false
(by default) so it is not shown/enumerated in the properties:
const myObj = { color: 'red', score: 8 };
Object.defineProperty(myObj, "greeting", {
enumerable: false,
writable: true,
value: "hello"
});
console.log(myObj.greeting);
console.log(myObj);
console.log(Object.values(myObj));
According to the documentation:
This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration (for...in loop or Object.keys method), whose values may be changed, and which may be deleted. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable and not enumerable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With