blob: e4006fe1290704ab50c49da3c73e206184a8c6eb [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001/*
2 * getobject
3 * https://github.com/cowboy/node-getobject
4 *
5 * Copyright (c) 2013 "Cowboy" Ben Alman
6 * Licensed under the MIT license.
7 */
8
9'use strict';
10
11var getobject = module.exports = {};
12
13// Split strings on dot, but only if dot isn't preceded by a backslash. Since
14// JavaScript doesn't support lookbehinds, use a placeholder for "\.", split
15// on dot, then replace the placeholder character with a dot.
16function getParts(str) {
17 return str.replace(/\\\./g, '\uffff').split('.').map(function(s) {
18 return s.replace(/\uffff/g, '.');
19 });
20}
21
22// Get the value of a deeply-nested property exist in an object.
23getobject.get = function(obj, parts, create) {
24 if (typeof parts === 'string') {
25 parts = getParts(parts);
26 }
27
28 var part;
29 while (typeof obj === 'object' && obj && parts.length) {
30 part = parts.shift();
31 if (!(part in obj) && create) {
32 obj[part] = {};
33 }
34 obj = obj[part];
35 }
36
37 return obj;
38};
39
40// Set a deeply-nested property in an object, creating intermediary objects
41// as we go.
42getobject.set = function(obj, parts, value) {
43 parts = getParts(parts);
44
45 var prop = parts.pop();
46 obj = getobject.get(obj, parts, true);
47 if (obj && typeof obj === 'object') {
48 return (obj[prop] = value);
49 }
50};
51
52// Does a deeply-nested property exist in an object?
53getobject.exists = function(obj, parts) {
54 parts = getParts(parts);
55
56 var prop = parts.pop();
57 obj = getobject.get(obj, parts);
58
59 return typeof obj === 'object' && obj && prop in obj;
60};