0

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' ]
5
  • 2
    do you have some data to test? and the (wanted) result? Commented Jul 8, 2019 at 17:23
  • i added an example to make it more clear. Commented Jul 8, 2019 at 17:27
  • please add the data of the call of the function as well. Commented Jul 8, 2019 at 17:30
  • it's the second line of the code snippet. or which call? i edited the argument value to the test snippet. Commented Jul 8, 2019 at 17:32
  • You might want to see the answers to stackoverflow.com/q/56066101 Commented Jul 8, 2019 at 19:35

1 Answer 1

2

You need to assign the path because strings are immuatable.

path = path.concat('.').concat(pitchfork);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, i did that and edited my question. But it's not quite what i wanted yet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.