-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
57 lines (53 loc) · 1.71 KB
/
index.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
'use strict';
/**
* @description
* returns {boolean} True if `value` is an `Object` but not `null`
* @param value
* @returns {boolean}
*/
function isObject(value) {
return value !== null && typeof value === 'object' && !(value instanceof Date);
}
/**
* @description
* Determines if a reference is an `Array`.
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
var isArray = Array.isArray;
function deepKeys(obj, stack, parent, intermediate) {
Object.keys(obj).forEach(function(el) {
// Escape . in the element name
var escaped = el.replace(/\./g, '\\\.');
// If it's a nested object
if(isObject(obj[el]) && !isArray(obj[el])) {
// Concatenate the new parent if exist
var p = parent ? parent + '.' + escaped : parent;
// Push intermediate parent key if flag is true
if (intermediate) stack.push(parent ? p : escaped);
deepKeys(obj[el], stack, p || escaped, intermediate);
} else {
// Create and save the key
var key = parent ? parent + '.' + escaped : escaped;
stack.push(key)
}
});
return stack
}
/**
* @description
* Get an object, and return an array composed of it's properties names(nested too).
* With intermediate equals to true, we include also the intermediate parent keys into the result
* @param obj {Object}
* @param intermediate {Boolean}
* @returns {Array}
* @example
* deepKeys({ a:1, b: { c:2, d: { e: 3 } } }) ==> ["a", "b.c", "b.d.e"]
* @example
* deepKeys({ b: { c:2, d: { e: 3 } } }, true) ==> ["b", "b.c", "b.d", "b.d.e"]
* @example
* deepKeys({ 'a.': { b: 1 }) ==> ["a\..b"]
*/
module.exports = function (obj, intermediate) {
return deepKeys(obj, [], null, intermediate);
};