From 198e8edf85351ad6a28c75e30c98a28753fb5244 Mon Sep 17 00:00:00 2001 From: jos Date: Fri, 30 Dec 2016 10:52:48 +0100 Subject: [PATCH] Fixed ordering of search results --- src/jsonData.js | 43 ++++++++++++++++++++++++------------------- test/jsonData.test.js | 8 ++++---- 2 files changed, 28 insertions(+), 23 deletions(-) diff --git a/src/jsonData.js b/src/jsonData.js index 3e7ee89..bc71761 100644 --- a/src/jsonData.js +++ b/src/jsonData.js @@ -517,27 +517,25 @@ export function search (data, text): SearchResult[] { let results: SearchResult[] = [] traverse(data, function (value, path, root) { - // search in values - if (value.type === 'value') { - if (containsCaseInsensitive(value.value, text)) { - results.push({ - dataPath: path, - type: 'value' - }) - } - } + // check property name + const prop = last(path) - // search object property names - if (value.type === 'Object') { - value.props.forEach((prop) => { - if (containsCaseInsensitive(prop.name, text)) { - results.push({ - dataPath: path.concat(prop.name), - type: 'property' - }) - } - }) + if (typeof prop === 'string' && containsCaseInsensitive(prop, text)) { + // only add search result when this is an object property name, + // don't add search result for array indices + const parentPath = path.slice(0, path.length - 1) + const parent = getIn(root, toDataPath(data, parentPath)) + if (parent.type === 'Object') { + results.push({ dataPath: path, type: 'property' }) } + } + + // check value + if (value.type === 'value') { + if (containsCaseInsensitive(value.value, text)) { + results.push({ dataPath: path, type: 'value' }) + } + } }) return results @@ -797,3 +795,10 @@ export function compileJSONPointer (path) { .map(p => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1')) .join('') } + +/** + * Returns the last item of an array + */ +function last (array: Array): any { + return array[array.length - 1] +} \ No newline at end of file diff --git a/test/jsonData.test.js b/test/jsonData.test.js index 887dec3..268b6f1 100644 --- a/test/jsonData.test.js +++ b/test/jsonData.test.js @@ -278,7 +278,7 @@ const JSON_DATA_EXAMPLE_SEARCH_L = { value: { type: 'value', value: 4, - searchProperty: 'normal' + searchProperty: 'active' } } ] @@ -302,7 +302,7 @@ const JSON_DATA_EXAMPLE_SEARCH_L = { value: { type: 'value', value: null, - searchProperty: 'active', + searchProperty: 'normal', searchValue: 'normal' } }, @@ -925,11 +925,11 @@ test('search', t => { // console.log(searchResults) t.deepEqual(searchResults, [ - {dataPath: ['nill'], type: 'property'}, - {dataPath: ['bool'], type: 'property'}, {dataPath: ['obj', 'arr', '2', 'last'], type: 'property'}, {dataPath: ['str'], type: 'value'}, + {dataPath: ['nill'], type: 'property'}, {dataPath: ['nill'], type: 'value'}, + {dataPath: ['bool'], type: 'property'}, {dataPath: ['bool'], type: 'value'} ])