/usr/lib/nodejs/obj-util/index.js is in node-obj-util 2.0.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | /**
*
* Module with utilities to set and retrieve values on an object using a `path`
* @class objUtil
* @static
*/
var objUtil = {
/**
* Returns the value from the given object which matches the passed key
*
* @method getKeyValue
* @param obj {Object} The object to get the values from
* @param key {String} a string representing a key in the object. Subkeys are supported
* separating them with dots. i.e. `key1.subkey1.subsubkey1`
* @returns {Mixed} the value of the given key in the passed obj
* @example
* ```javascript
* var objUtil = require('obj-util');
*
* var obj = {
* some: {
* key: 'some value'
* }
* };
*
* objUtil.getKeyValue(obj, 'some.key'); // 'some value'
*
* ```
*/
getKeyValue: function ( obj, key ) {
if ( !obj ) {
return null;
}
var temp = obj,
keys = key.split( '.' );
for (var ix = 0; ix < keys.length; ix++) {
var theKey = keys[ ix ];
temp = temp[ theKey ];
if (typeof temp === 'undefined') {
return undefined;
}
if ( temp === null ) {
return null;
}
}
return temp;
},
/**
* Sets a value in an object if a matching key is found inside the given object
*
* @method setKeyValue
* @param obj {Object} the object where to set the value using if the key is found
* @param key {String} a string that represents the key. Subkeys are supported by separating them with dots.
* @param val the value to be set in the object
* @example
* ```javascript
* var objUtil = require('obj-util');
*
* var obj = {
* };
* objUtil.setKeyValue(obj, 'some.key', 'some value');
* obj.some.key === 'some value' //==> true
* ```
*/
setKeyValue: function ( obj, key, val ) {
if ( !obj ) {
return;
}
var temp = obj,
keys = key.split( '.' );
for (var ix = 0, len = keys.length; ix < len; ix++) {
var theKey = keys[ ix ],
t = temp[ theKey ];
if ( typeof t === 'undefined' || t === null ) {
var isPrevLast = (ix < len - 1);
temp[ theKey ] = isPrevLast ? {} : val;
if ( isPrevLast ) {
temp = temp[ theKey ];
}
} else {
if ( ix < len ) {
temp = t;
}
}
}
}
};
module.exports = objUtil;
|