gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:51:28 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于javascript - js中递归搜索返回路径的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56939826/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com