【问题标题】:Recursive search of objects returning the path in js在js中递归搜索返回路径的对象
【发布时间】:2019-07-09 03:32:52
【问题描述】:

我正在编写一个函数来搜索嵌套的 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' ]

【问题讨论】:

  • 你有一些数据要测试吗?和(想要的)结果?
  • 我添加了一个示例以使其更清晰。
  • 请同时添加函数调用的数据。
  • 这是代码sn-p的第二行。或哪个电话?我将argument 值编辑为测试sn-p。
  • 您可能想查看stackoverflow.com/q/56066101的答案

标签: javascript recursion search


【解决方案1】:

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

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

【讨论】:

  • 是的,我这样做并编辑了我的问题。但这还不是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
  • 2019-11-04
相关资源
最近更新 更多