diff --git a/README.md b/README.md index 3295f75..7e21929 100644 --- a/README.md +++ b/README.md @@ -159,9 +159,25 @@ 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 @@ -169,7 +185,7 @@ npx flat foo.json ``` Or install the `flat` command globally: - + ```sh npm i -g flat && flat foo.json ``` diff --git a/index.js b/index.js index ca8904a..8bc0102 100644 --- a/index.js +++ b/index.js @@ -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)) { diff --git a/test/test.js b/test/test.js index 541c9d7..a65f708 100644 --- a/test/test.js +++ b/test/test.js @@ -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); + }) })