Skip to content

Commit

Permalink
Merge 15d600d into 16cd831
Browse files Browse the repository at this point in the history
  • Loading branch information
nabiltntn committed Jan 21, 2016
2 parents 16cd831 + 15d600d commit 4ec119d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 12 deletions.
32 changes: 20 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,7 @@ function isObject(value) {
*/
var isArray = Array.isArray;

/**
* @description
* Get an object, and return an array composed of it's properties names(nested too).
* @param obj {Object}
* @param stack {Array}
* @param parent {String}
* @returns {Array}
* @example
* parseKeys({ a:1, b: { c:2, d: { e: 3 } } }) ==> ["a", "b.c", "b.d.e"]
*/
module.exports = function deepKeys(obj, stack, parent) {
var deepKeysWithIntermediate = function(obj, stack, parent, intermediate) {
stack = stack || [];
var keys = Object.keys(obj);

Expand All @@ -37,12 +27,30 @@ module.exports = function deepKeys(obj, stack, parent) {
if(isObject(obj[el]) && !isArray(obj[el])) {
//concatenate the new parent if exist
var p = parent ? parent + '.' + el : parent;
deepKeys(obj[el], stack, p || el);
//Push intermediate parent key if flag is true
intermediate && stack.push(parent ? p:el);
deepKeysWithIntermediate(obj[el], stack, p || el, intermediate);
} else {
//create and save the key
var key = parent ? parent + '.' + el : el;
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 } } }) ==> ["b", "b.c", "b.d", "b.d.e"]
*/
module.exports = function deepKeys(obj, intermediate) {
return deepKeysWithIntermediate(obj, [], null, intermediate);
};
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,18 @@ describe('deep-keys', function() {
'isActive'
]);
});

it('should return deep keys including intermediate parent keys', function() {
var obj1 = {
a: 1,
b: { c: 1 },
c: { d: { e: 1 }, f: 1 },
d: { e: { f: { g: 1, h: 2 } } },
e: 2,
f: { g: [] }
};
expectEqual(keys(obj1, true), ['a', 'b', 'b.c', 'c', 'c.d', 'c.d.e', 'c.f',
'd', 'd.e', 'd.e.f', 'd.e.f.g', 'd.e.f.h', 'e', 'f', 'f.g']);
});

});

0 comments on commit 4ec119d

Please sign in to comment.