forked from ServiceNowDevProgram/code-snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomObjectUtils.js
61 lines (52 loc) · 1.57 KB
/
CustomObjectUtils.js
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
var CustomObjectUtils = Class.create();
CustomObjectUtils.prototype = {
initialize: function(useES12 = false) {
if (useES12) {
this.safeAccess = this.safeAccessModern;
}
},
// ====================
// ES5 Functions
// ====================
/**SNDOC
@name safeAccess
@description Safely accesses nested object properties.
@param {Object} obj - The object to access.
@param {string} path - The dot-separated path to the property.
@returns {*} The accessed value or false if not found.
@example
var myObj = { a: { b: { c: 42 } } };
safeAccess(myObj, 'a.b.c');
// Returns: 42
*/
safeAccess: function(obj, path) {
var parts = path.split('.');
for (var i = 0; i < parts.length; i++) {
if (obj && obj.hasOwnProperty(parts[i])) {
obj = obj[parts[i]];
} else {
return false;
}
}
return obj;
},
// ====================
// ECMAScript 2021 (ES12)
// ====================
/**SNDOC
@name safeAccessModern
@description Safely accesses nested object properties.
@param {Object} obj - The object to access.
@param {string} path - The dot-separated path to the property.
@returns {*} The accessed value or false if not found.
@example
const myObj = { a: { b: { c: 42 } } };
safeAccess(myObj, 'a.b.c');
// Returns: 42
*/
safeAccessModern: function(obj, path) {
const value = path.split('.').reduce((o, key) => o?.[key], obj);
return value ?? false;
},
type: 'CustomObjectUtils'
};