javascript - 在嵌套对象中搜索键/值 (JavaScript)
问题描述
我试图在嵌套对象中找到一个对象值,这个对象有很多 o 级别,而我想要的这个特定对象值并不总是在对象内部的同一级别。
我想做的是:
//ArrayofCoordinates it's the array of the objects that i want to search my value inside of each of this objects.
let coordinatesToAddArray = [];
arrayOfCoordinates.map(coordinateObject => {
let coordinateData = findObjectNested(coordinateObject, 'tagName', 'text'); //'tagName' it's the key that i'm looking for and 'text' it's the value of the 'tagName' key that i'm looking for.
if(coordinateData) {
coordinatesToAddArray.push(coordinateData);
}
});
//This is the recursive function that i created to search inside the object for the specific value and return him, but all i get from the return of this function it's a undefined.
function findObjectNested(entireObj, keyToFind, valueToFind) {
if(entireObj && entireObj[keyToFind] === valueToFind) {
return entireObj;
} else {
if(entireObj['children'].length > 0) {
entireObj['children'].map(objectsOfChildren => {
findObjectNested(objectsOfChildren, keyToFind, valueToFind);
});
}
}
}
我知道它正在工作的递归函数,因为当我将“return wholeObj”替换为“console.log(entireObj)”时,我可以看到我正在寻找的对象,但是当我试图返回这个对象时,我得到它是一个未定义的。
我相信这与递归函数有关。
任何人都可以帮助我提供有关如何解决此问题的任何提示?
太感谢了。