递归搜索对象返回js中的路径

时间:2019-07-08 17:22:05

标签: javascript recursion search

我正在编写一个函数,用于在嵌套js对象中搜索键或值,并返回匹配及其路径。 目前,搜索阶段的路径串联尚不起作用。也许有人可以给我提示。

给出此测试数据:

let object = {
    'id' : '1',
    'items' : [
        'knive', 'blue flower', 'scissor'
    ],
    'nested' : {
        'array1' : ['gold', 'silver'],
        'array2' : ['blue', 'knive'],
    }

}

let argument = 'knive';

和此代码:


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);
        }
    }
}

我得到以下结果:

[ 'key: 0, value: knive, path: items',
  'key: 1, value: knive, path: items.nested.array1.array2' ]

但是我想拥有那些:

[ 'key: 0, value: knive, path: items',
  'key: 1, value: knive, path: nested.array2' ]

1 个答案:

答案 0 :(得分:2)

因为字符串是不可改变的,所以您需要分配path

path = path.concat('.').concat(pitchfork);