![](/img/trans.png)
[英]Find the object by key & value in JSON in case that I don't know the structure of JSON which is single, array or nested deep structure
[英]Find a specific value in a object with key but i don't know the path
我有一個這樣的對象:例如。
{a:"aaaa",
b:{
b1:"1b1b1b",
b2:"2bb22b",
b3:{
mykey:"value to find",
some:"same",
},
},
}
我知道鍵“ mykey”,但我不知道它在哪里,我不知道路徑...我不能這樣使用它來找到值...
myObj.a.b.maykey
因為我不知道密鑰“ mykey”在哪里,我只知道我的對象中有這個密鑰
我必須找到“要查找的值”,如何找到myKey的值?
謝謝
假設您知道鍵是myKey
並且正在對象圖中的某個位置尋找它,一個選擇是使用深度優先遍歷遞歸函數(類似於DOM用於querySelector
函數)。 這比顧名思義要簡單得多。 :-) 看評論:
function findFirstValue(data, key) { // ASSERTION: data is an object // Loop through the properties of the object for (const [name, value] of Object.entries(data)) { // Found the key? if (name === key) { // Return the value return value; } // If the value is an object, recurse if (typeof value === "object") { const found = findFirstValue(value, key); if (found !== undefined) { // Found during recursion return found; } } } // Not found return undefined; // Explicit, but this is effectively what would happen anyway } const found = findFirstValue({ a: "aaaa", b: { b1: "1b1b1b", b2: "2bb22b", b3: { mykey: "value", some: "same", }, }, }, "mykey"); console.log(found);
如果找不到,則返回undefined
。 您可以改用標志值(這樣,如果找到了鍵,但該值實際上是undefined
,則可以分辨出該值)。 這是對上面的細微調整。 但是,如果您可以假設該值實際上不是undefined
,則undefined
是可以使用的良好標志值。
您可以通過遞歸來做到這一點。
let obj = {a:"aaaa", b:{ b1:"1b1b1b", b2:"2bb22b", b3:{ mykey:"value", some:"same", }, }, } function find(obj,givenKey){ for(let key in obj){ //checks if key's value is object if(typeof obj[key] === "object"){ //find 'givenKey' inside that object let keyValue = find(obj[key],givenKey) //if 'givenKey' is found in that object if(keyValue){ //return that key's value return keyValue } } //if key's value is not object else{ //if key match given key then it return the value of key if(key === givenKey) return obj[key] } } } console.log(find(obj,'mykey'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.