From 0453680d406afc82a88dbe1fb9816baad87c92af Mon Sep 17 00:00:00 2001 From: Ciprian Florescu Date: Wed, 11 Dec 2019 15:42:37 +0200 Subject: [PATCH] Added ignoreValue option --- README.md | 30 ++++++++++++++++++++++++++++++ index.js | 3 ++- test/test.js | 24 ++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a036a9f..827f292 100644 --- a/README.md +++ b/README.md @@ -208,6 +208,36 @@ unflatten({ // } ``` +### ignoreValue + +Ignore specific values from flattening. + +```javascript +var flatten = require('flat') +var unflatten = require('flat').unflatten + +flatten({ + key1: { + keyA: 'valueI' + }, + key2: { + keyB: 'valueII' + }, + key3: { a: { b: { c: 2 } } } +}, { + ignoreValue: function(value){ + return !!value.c; + } +}) + +// { +// 'key1.keyA': 'valueI', +// 'key2.keyB__': 'valueII', +// 'key3.a.b': {'c':2}, +// } + +``` + ## Command Line Usage `flat` is also available as a command line tool. You can run it with diff --git a/index.js b/index.js index c8032e9..13c2ea4 100644 --- a/index.js +++ b/index.js @@ -33,7 +33,8 @@ function flatten (target, opts) { : transformKey(key) if (!isarray && !isbuffer && isobject && Object.keys(value).length && - (!opts.maxDepth || currentDepth < maxDepth)) { + (!opts.maxDepth || currentDepth < maxDepth) && + (!opts.ignoreValue || !opts.ignoreValue(value))) { return step(value, newKey, currentDepth + 1) } diff --git a/test/test.js b/test/test.js index d86d396..ad5376b 100644 --- a/test/test.js +++ b/test/test.js @@ -206,6 +206,30 @@ suite('Flatten', function () { 'hello.0500': 'darkness my old friend' }) }) + + test('Ignore Values', function () { + assert.deepStrictEqual(flatten({ + hello: { + world: { + again: 'good morning' + } + }, + lorem: { + ipsum: { + dolor: 'good evening' + } + } + }, { + ignoreValue: function (value) { + return !!value.again; + } + }), { + 'hello.world': { + again: 'good morning' + }, + 'lorem.ipsum.dolor': 'good evening' + }) + }); }) suite('Unflatten', function () {