Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,30 @@ flatten({
// 'key3.a': { b: { c: 2 } }
// }
```

### uniformFlatten

If maxDepth is set, will flatten each object in the collection to the depth specified by maxDepth. This uniformly flattens the object at the depth specified.

This is usually set in combination with the maxDepth option.

``` javascript
var flatten = require('flat')

flatten({
key1: {
keyA: {a: 'valueI'}
},
key2: {
keyB: {a: {b: 'valueII'}}
},
key3: { a: { b: { c: 2 } } }
}, { maxDepth: 2, uniformFlatten: true})


//{
// 'key1.keyA.a': 'valueI',
// 'key2.keyB.a': { b: 'valueII' },
// 'key3.a.b': { c: 2 }
//}
```
23 changes: 12 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ function flatten(target, opts) {

var delimiter = opts.delimiter || '.'
var maxDepth = opts.maxDepth
var currentDepth = 1
var output = {}

function step(object, prev) {
Object.keys(object).forEach(function(key) {
var output = {};
var numberToFlatten = 1;
function step(object, prev, currentDepth) {
currentDepth = currentDepth || 1;
Object.keys(object).forEach(function(key) {
var value = object[key]
var isarray = opts.safe && Array.isArray(value)
var type = Object.prototype.toString.call(value)
Expand All @@ -26,19 +26,20 @@ function flatten(target, opts) {
: key

if (!opts.maxDepth) {
maxDepth = currentDepth + 1;
maxDepth = numberToFlatten + 1;
}

if (!isarray && !isbuffer && isobject && Object.keys(value).length && currentDepth < maxDepth) {
++currentDepth
return step(value, newKey)
var flattenCondition = (opts.uniformFlatten) ? currentDepth : numberToFlatten
if (!isarray && !isbuffer && isobject && Object.keys(value).length && flattenCondition < maxDepth) {
++numberToFlatten;
return step(value, newKey, currentDepth + 1)
}

output[newKey] = value
})
}

step(target)
step(target);

return output
}
Expand Down
24 changes: 23 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,29 @@ suite('Flatten', function() {
}
})
})
})

test('Uniform Flatten with Depth', function(){
assert.deepEqual(flatten({
hello: {
world: {again: 'good morning'}
},
salut: {
monde: {encore: {bonne: 'matin'}}
},
konnichiwa: { sekai: { mou: { ohayou: 'gozaimasu' } } }
}, {
maxDepth: 3,
uniformFlatten: true
}),
{
'hello.world.again': 'good morning',
'salut.monde.encore': { bonne: 'matin' },
'konnichiwa.sekai.mou': { ohayou: 'gozaimasu' }
});
})
});



suite('Unflatten', function() {
test('Nested once', function() {
Expand Down