forked from GrosSacASac/JavaScript-Set-Up
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObject.js
More file actions
102 lines (76 loc) · 2.3 KB
/
Copy pathObject.js
File metadata and controls
102 lines (76 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* Knowledge about Object */
/* How to create an empty Object ? */
let anObject;
// same
anObject = Object.create(Object.prototype);
anObject = Object();
anObject = {};
// without prototype
anObject = Object.create(null);
// creating with prefilled properties
anObject = {
"key1": "value1",
"key2": "value2",
};
// assign simple
anObject["key"] = "value";
// assign multiple
Object.assign(anObject, {
"key1": "value1",
"key2": "value2"
});
// get a specific value
anObject["key"];
// get Length
Object.keys(anObject).length;
Object.values(anObject).length;
Object.entries(anObject).length;
// iterate over
// keys only
Object.keys(anObject).forEach(function (key) {
});
// values only
Object.values(anObject).forEach(function (value) {
});
// keys and values
Object.entries(anObject).forEach(function ([key, value]) {
});
// iterate over the object and its full prototype chain
let key;
for (key in anObject) {
const value = anObject[key];
}
// iterate over all own Properties including Symbols and non-enumerables (anti-pattern)
Reflect.ownKeys(anObject).forEach(function (key) {
const value = anObject[key];
});
// iterate over own Properties including non-enumerables (anti-pattern)
Object.getOwnPropertyNames(anObject).forEach(function (key) {
const value = anObject[key];
});
// has a key
anObject.hasOwnProperty("key");
// has safe, works even when anObject has a key "hasOwnProperty"
// also works for Objects without prototype
Object.prototype.hasOwnProperty.call(anObject, "key");
// has a key, or it can be found in the prototype chain
"key" in anObject;
Reflect.has(anObject, "key");
// remove a value
anObject["key"] = undefined;
// completly remove a property (key and value)
delete anObject["key"];
// prevent future extensions
Object.preventExtensions(anObject);
anObject["newThing"] = 2; // Error in strict mode
// prevent future extensions and removals
anObject["beforeSealing"] = 10;
Object.seal(anObject);
anObject["newThing"] = 2; // Error in strict mode
delete anObject["beforeSealing"]; // Error in strict mode
// prevent future extensions and removals and mutations
anObject["beforeSealing"] = 10;
Object.freeze(anObject);
anObject["newThing"] = 2; // Error in strict mode
delete anObject["beforeSealing"]; // Error in strict mode
anObject["beforeSealing"] = 11; // Error in strict mode