簡體   English   中英

如何訪問給定動態鍵的嵌套對象的屬性?

[英]How to access property of nested object given dynamic keys?

我有一個不知道其結構的嵌套對象。 例如:

const nestedObject = {
  "one": {
    "two": {
       "three": 3
     }
  }
}

我想顯示three值。

我有一個這樣的數組,以便我知道如何導航對象以達到three

const keys = ["one", "two", "three"]

不必以這種方式構造。

那么,如何根據上述keys數組訪問one.two.three 或其他一些數據結構。 我本來打算進行遞歸,但它似乎太復雜了,我覺得這里有一個簡單的解決方案。

您可以使用簡單的Array.prototype.reduce()函數完成此操作:

 const data = { "one": { "two": { "three": 3 } } }; const keys = ["one", "two", "three"]; const value = keys.reduce((a, v) => a[v], data); console.log(value); 

您可以使用MyObject["fieldName"]訪問子對象。 然后,您可以使用遞歸函數,該函數將使用包含索引的數組漫游對象

 let MyObj = { "one": { "two": { "three": 3 } } }; let Keys = ["one", "two", "three"]; function getValue(obj, arrIndexes, index = 0) { let currentIndex = arrIndexes[index]; let currentObject = obj[currentIndex]; if (index < arrIndexes.length - 1) { return getValue(currentObject, arrIndexes, index + 1) } else { return currentObject; } } console.log(getValue(MyObj, Keys)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM