Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript add hidden data to Object

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.

like image 936
Max888 Avatar asked Dec 30 '22 22:12

Max888


1 Answers

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.

like image 192
Majed Badawi Avatar answered Jan 13 '23 18:01

Majed Badawi