深度搜索是 javascript 中的对象
Deep search is object in javascript
我正在尝试搜索 JavaScript 中对象中的任何对 key:value 和它所属的子对象 return。
到目前为止我所做的并没有return我预期的对象,我找不到原因。
function searchSheet(obj, keyName, valName) {
let found
for (prop in obj) {
if (typeof obj[prop] == "object") {
searchSheet(obj[prop], keyName, valName);
} else {
if (prop === keyName && obj[prop] === valName) {
found = obj
console.log(found);
// found is logged correctly here
return found
// …but nothing is returned here
}
}
}
}
let sheet = {
"config": {},
"patterns": {
"id": 0,
"type": "pattern",
"startTime": 1652193369859,
"synth": "tic",
"keys": [{
"id": 1,
"type": "key",
"keyCode": 73,
"startTime": 1652193369960,
"note": 730,
"offset": "12.1"
},
{
"id": 2,
"type": "key",
"keyCode": 82,
"startTime": 1652193370371,
"note": 820,
"offset": "61.2"
}
],
"endTime": 1652193370695,
"duration": 836,
"loop": 35
}
}
console.log(
searchSheet(sheet, "keyCode", 82) // undefined
)
Ian Brindley 的评论部分正确。您正在丢弃递归调用的 return 值。您可以通过更改此
来修复您的代码
if (typeof obj[prop] == "object") {
searchSheet(obj[prop], keyName, valName);
} else { //...
至此
if (typeof obj[prop] == "object") {
let objectFound = searchSheet(obj[prop], keyName, valName);
if (objectFound !== undefined) return objectFound
} else { //...
还有其他方法,尤其是使用嵌套辅助函数的方法。
我正在尝试搜索 JavaScript 中对象中的任何对 key:value 和它所属的子对象 return。
到目前为止我所做的并没有return我预期的对象,我找不到原因。
function searchSheet(obj, keyName, valName) {
let found
for (prop in obj) {
if (typeof obj[prop] == "object") {
searchSheet(obj[prop], keyName, valName);
} else {
if (prop === keyName && obj[prop] === valName) {
found = obj
console.log(found);
// found is logged correctly here
return found
// …but nothing is returned here
}
}
}
}
let sheet = {
"config": {},
"patterns": {
"id": 0,
"type": "pattern",
"startTime": 1652193369859,
"synth": "tic",
"keys": [{
"id": 1,
"type": "key",
"keyCode": 73,
"startTime": 1652193369960,
"note": 730,
"offset": "12.1"
},
{
"id": 2,
"type": "key",
"keyCode": 82,
"startTime": 1652193370371,
"note": 820,
"offset": "61.2"
}
],
"endTime": 1652193370695,
"duration": 836,
"loop": 35
}
}
console.log(
searchSheet(sheet, "keyCode", 82) // undefined
)
Ian Brindley 的评论部分正确。您正在丢弃递归调用的 return 值。您可以通过更改此
来修复您的代码if (typeof obj[prop] == "object") {
searchSheet(obj[prop], keyName, valName);
} else { //...
至此
if (typeof obj[prop] == "object") {
let objectFound = searchSheet(obj[prop], keyName, valName);
if (objectFound !== undefined) return objectFound
} else { //...
还有其他方法,尤其是使用嵌套辅助函数的方法。