I am writing a function to search nested js objects for keys or values, returning hits and their paths. At the moment, the path concatenation of the search stages does not work yet. Maybe someone can give me a hint.
Given this test data:
let object = {
'id' : '1',
'items' : [
'knive', 'blue flower', 'scissor'
],
'nested' : {
'array1' : ['gold', 'silver'],
'array2' : ['blue', 'knive'],
}
}
let argument = 'knive';
and this code:
let pincushion = [];
find(argument, object, pincushion);
function find(needle, heyheap, pincushion, path = '') {
for (let pitchfork in heyheap) {
if (typeof(heyheap[pitchfork]) === 'object') {
if (path.length == 0) {
path = pitchfork.toString();
} else {
path = path.concat('.').concat(pitchfork);
}
find(needle, heyheap[pitchfork], pincushion, path);
if (path.length > 0) {
let split = path.split('.');
path = path.substring(0, path.length - split[split.length - 1].length - 1);
}
} else if (pitchfork === needle || heyheap[pitchfork] === needle) {
let key = pitchfork.toString();
let value = heyheap[pitchfork].toString();
let pin = 'key: '.concat(key).concat(', value: ').concat(value).concat(', path: ').concat(path);
pincushion.push(pin);
}
}
}
i get following results:
[ 'key: 0, value: knive, path: items',
'key: 1, value: knive, path: items.nested.array1.array2' ]
but i want to have those:
[ 'key: 0, value: knive, path: items',
'key: 1, value: knive, path: nested.array2' ]