Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add key and value interceptor function to manipulate this values #81

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
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
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,17 +159,33 @@ flatten({
// }
```

### Key interceptor for flatten

Give the possibility to manipulate the key (Ex: Translate)

``` javascript
var flatten = require('flat')
var data = { name: 'Rodolfo', age: 29 };

flatten(data, { maxDepth: 2, keyInterceptor: key => I18n.t(`myModule.${key}`) })

// {
// 'Nome completo': 'Rodolfo',
// 'Idade': 29
// }
```

## Command Line Usage

`flat` is also available as a command line tool. You can run it with
`flat` is also available as a command line tool. You can run it with
[`npx`](https://ghub.io/npx):

```sh
npx flat foo.json
```

Or install the `flat` command globally:

```sh
npm i -g flat && flat foo.json
```
Expand Down
16 changes: 13 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,19 @@ function flatten (target, opts) {
type === '[object Array]'
)

var newKey = prev
? prev + delimiter + key
: key
var newKey = key

if (opts.keyInterceptor) {
newKey = opts.keyInterceptor(newKey)
}

if (opts.valueInterceptor) {
value = opts.valueInterceptor(newKey, value)
}

newKey = prev
? prev + delimiter + newKey
: newKey

if (!isarray && !isbuffer && isobject && Object.keys(value).length &&
(!opts.maxDepth || currentDepth < maxDepth)) {
Expand Down
42 changes: 42 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -510,4 +510,46 @@ suite('Arrays', function () {
}
})
})

test('Should be translate the keys', function () {
var originalData = {
name: 'Rodolfo', age: 27
};

var expectedData = {
'Nome': 'Rodolfo',
'Idade': 27
};

var translates = {
name: 'Nome',
age: 'Idade'
};

var options = {
keyInterceptor: function(key) {
return translates[key];
}
}

assert.deepEqual(flatten(originalData, options), expectedData);
})

test('Should be sum the value', function () {
var originalData = {
name: 'Rodolfo', age: 20
};

var expectedData = {
name: 'Rodolfo', age: 50
};

var options = {
valueInterceptor: function(key, value) {
return key === 'age' ? value + 30 : value
}
}

assert.deepEqual(flatten(originalData, options), expectedData);
})
})