From 556645844d1a6b4c55c1c8d662d022fb69f526c1 Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Mon, 29 Jun 2020 12:37:28 +0200 Subject: [PATCH] filter out undefined fields --- index.js | 17 ++++++++--------- test/index.js | 25 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index c78212d..b74bdd0 100644 --- a/index.js +++ b/index.js @@ -93,15 +93,14 @@ function recursive_filter (input, filters, children_key = 'children') { data[i] = e; let match = true; for (const filter of filters) { - 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]; } + const is_multi_filter + = Array.isArray (filter.fields); + + const search_str = is_multi_filter + ? filter.fields.map ((f) => e[f]) + .filter ((v) => typeof v !== 'undefined') + .join (' ') + : e[filter.field]; if (!filter.filter.test (search_str)) { match = false; diff --git a/test/index.js b/test/index.js index d6e3b3d..dbd6b23 100644 --- a/test/index.js +++ b/test/index.js @@ -188,3 +188,28 @@ test ('recursive filter multifield', (t) => { const result = util.recursive_filter (raw, [ filter ]); t.deepEqual (filtered, result); }); + +test ('recursive filter multifield input error', (t) => { + t.notThrows (() => { + util.recursive_filter ( + [ { foo: 'bar' } ], + [ { fields: '', field: 'foo', filter: /a/u } ] + ); + }); +}); + +test ('recursive filter undefined multifield', (t) => { + const res = util.recursive_filter ( + [ { foo: 'bar' } ], + [ + { + fields: [ + 'foo', + 'bar' + ], + filter: /\s/u + } + ] + ); + t.deepEqual (res, []); +});