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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,30 @@ unflatten({
// }
```

### arrayBrackets

When enabled, array children will be wrapped in brackets:

``` javascript
flatten({
arr: [
'a',
'b'
],
arr2: [
{
keyB: 'valueII'
}
]
}, { arrayBrackets: true })

// {
// 'arr[0]': 'a',
// 'arr[1]': 'b',
// 'arr2[0].keyB': 'valueII'
// }
```

### overwrite

When enabled, existing keys in the unflattened object may be overwritten if they cannot hold a newly encountered nested value:
Expand Down
21 changes: 15 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ function flatten (target, opts) {
const delimiter = opts.delimiter || '.'
const maxDepth = opts.maxDepth
const transformKey = opts.transformKey || keyIdentity
const arrayBrackets = opts.arrayBrackets || false
const output = {}

function step (object, prev, currentDepth) {
function step (object, prev, currentDepth, addbrackets) {
currentDepth = currentDepth || 1
Object.keys(object).forEach(function (key) {
const value = object[key]
Expand All @@ -32,14 +33,22 @@ function flatten (target, opts) {
type === '[object Object]' ||
type === '[object Array]'
)

const newKey = prev
? prev + delimiter + transformKey(key)
: transformKey(key)
const childhasbrackets = arrayBrackets && Array.isArray(value)

let newKey
if (addbrackets) {
newKey = prev
? prev + '[' + transformKey(key) + ']'
: '[' + transformKey(key) + ']'
} else {
newKey = prev
? prev + delimiter + transformKey(key)
: transformKey(key)
}

if (!isarray && !isbuffer && isobject && Object.keys(value).length &&
(!opts.maxDepth || currentDepth < maxDepth)) {
return step(value, newKey, currentDepth + 1)
return step(value, newKey, currentDepth + 1, childhasbrackets)
}

output[newKey] = value
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,26 @@ suite('Flatten', function () {
})
})

test('Array Brackets', function () {
assert.deepStrictEqual(flatten({
hello: [
{
world: {
again: 'good morning'
}
}
],
arr: [1, 2, 3]
}, {
arrayBrackets: true
}), {
'hello[0].world.again': 'good morning',
'arr[0]': 1,
'arr[1]': 2,
'arr[2]': 3
})
})

test('Empty Objects', function () {
assert.deepStrictEqual(flatten({
hello: {
Expand Down