diff --git a/Jenkinsfile b/Jenkinsfile index f0463ff..e75c28a 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -5,7 +5,7 @@ pipeline { VERSION = VersionNumber([ versionNumberString: '${BUILDS_ALL_TIME}', - versionPrefix: '1.4.', + versionPrefix: '1.5.', worstResultForIncrement: 'SUCCESS' ]) } diff --git a/README.md b/README.md index ac0932e..1fbbd50 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # @sapphirecode/utilities -version: 1.4.x +version: 1.5.x small utility functions to make much needed features easier to work with @@ -110,6 +110,21 @@ console.log(JSON.stringify(result, null, 2)); ]*/ ``` +filters can also apply to multiple fields + +```js +const result = util.recursive_filter( + [{name: 'foo', name_2: 'bar'}], + [ + { + filter: /foo bar/iu, + fields: ['name', 'name_2'] // fields will be joined with a space in between + // {name: 'foo', name_2: 'bar'} will become 'foo bar' + } + ] +); +``` + ## License MIT © Timo Hocker diff --git a/index.js b/index.js index 64e691d..39e7fe1 100644 --- a/index.js +++ b/index.js @@ -91,7 +91,17 @@ function recursive_filter (input, filters, children_key = 'children') { for (const e of data) { let match = true; for (const filter of filters) { - if (!filter.filter.test (e[filter.field])) { + let search_str = ''; + if ( + typeof filter.fields !== 'undefined' + && Array.isArray (filter.fields) + ) { + search_str = filter.fields.map ((f) => e[f]) + .join (' '); + } + else { search_str = e[filter.field]; } + + if (!filter.filter.test (search_str)) { match = false; break; } diff --git a/test/index.js b/test/index.js index ee4e56b..6789462 100644 --- a/test/index.js +++ b/test/index.js @@ -147,3 +147,39 @@ test ('recursive filter', (t) => { const result = util.recursive_filter (raw, [ filter ]); t.deepEqual (filtered, result); }); + +test ('recursive filter multifield', (t) => { + const raw = [ + { name: 'foo', f: 'include' }, + { + name: 'include_bar', + children: [ + { name: 'foo' }, + { name: 'bar' } + ] + }, + { + name: 'baz', + children: [ + { name: 'include_foo' }, + { name: 'bar' } + ] + }, + { + name: 'barbaz', + children: [ + { name: 'foo' }, + { name: 'bar' } + ] + } + ]; + const filtered = [ + { name: 'foo', f: 'include' } + ]; + const filter = { + fields: ['name', 'f'], + filter: /foo include/ui + }; + const result = util.recursive_filter (raw, [ filter ]); + t.deepEqual (filtered, result); +});