Skip to content

Commit

Permalink
Add onlyLeaves option
Browse files Browse the repository at this point in the history
  • Loading branch information
andreaazzini committed Sep 24, 2016
1 parent 3d41b4b commit dcb865e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
12 changes: 5 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module.exports = function (options) {
options = options || {}
var blacklist = options.blacklist || []
var separator = options.separator == null ? '.' : options.separator
var onlyLeaves = options.onlyLeaves && true

return flatten

Expand All @@ -16,21 +17,18 @@ module.exports = function (options) {
}

function iterator (obj, prefix, flattened) {
var n = 0
var keys = Object.keys(obj)
var len = keys.length
var key, val

for (; n < len; n++) {
key = keys[n]
val = obj[key]
for (var n = 0; n < keys.length; n++) {
var key = keys[n]
var val = obj[key]

if (isObj(val) && !isBlacklisted(val)) {
iterator(val, prefix + key + separator, flattened)
continue
}

flattened[prefix + key] = val
onlyLeaves ? flattened[key] = val : flattened[prefix + key] = val
}
}

Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,17 @@ test('support empty string separator', function (t) {

t.end()
})

test('support no prefix', function (t) {
var obj = {
sub: { foo: 1, bar: { baz: 3 } }
}
var flatten = Flatten({ onlyLeaves: true })

t.deepEqual(flatten(obj), {
'foo': 1,
'baz': 3
})

t.end()
})

0 comments on commit dcb865e

Please sign in to comment.