簡體   English   中英

如何使用變量名訪問Javascript循環中嵌套對象內的元素?

[英]How to access elements inside nested objects in a Javascript loop using variable names?

我很無能為力。 我有一個像這樣的JSON字符串,我需要檢查提供的“屬性”(以下示例中的postsome ):

var index_file =
[{
 "indexAB":[
    { "postsome": ["keyword_abc", "keyword_def"] },
    { "testsome": ["keyword_111", "keyword_222"] }
  ]
},{
 "index_random": [
    { "postsome": ["keyword_abc"] }
  ]
}]

我有任意數量的索引(“indexAB”,“index_random”),里面有n對象。

我需要“找到”我的屬性postsome但我無法讓它工作,因為我正在努力正確的訪問對象的方式。

所以:

for (var i = 0, l = indices.length; i < l; i += 1) {

        doc._id = "postsome",
        index_name = "indexAB";

    indices[i]["indexAB"];             // ok, returns object on correct iteration
    indices[i][index_name];            // undefined
    indices[i].indexAB[0][doc._id]     // ok, returns undefined or keywords
    indices[i][index_name][0][doc._id] // undefined 
}

題:
如何使用變量名index_name訪問循環中的嵌套對象?

這不是您問題的直接答案,但我相信它實際上可能對您提供一種復雜的方法來幫助您訪問對象中的值。

如果不是這個JSON對象:

var index_file =
[{
 "indexAB":[
    { "postsome": ["keyword_abc", "keyword_def"] },
    { "testsome": ["keyword_111", "keyword_222"] }
  ]
},{
 "index_random": [
    { "postsome": ["keyword_abc"] }
  ]
}];

你會有這么簡單的數據結構:

var index_file =
{
  "indexAB": {
    "postsome": ["keyword_abc", "keyword_def"],
    "testsome": ["keyword_111", "keyword_222"]
  },
  "index_random": {
    "postsome": ["keyword_abc"]
  }
};

然后使用以下內容訪問會容易:

var value = index_file.indexAB.postsome[0]; // no loops, no nothing
//  value == "keyword_abc"

見: DEMO

我認為您應該更改的是您的數據模型,因為目前它與JSON的想法相差甚遠,並且訪問數據總是非常困難。

幾個問題

  • “indexAB”僅存在於數組中的第一個元素上
  • 變量名稱中不能包含點。

我建議你在進一步引用它之前測試indexAB是否是對象的屬性。 見下面的例子:

固定

var indices = index_file;
for (var i = 0, l = indices.length; i < l; i++) {

    var doc_id = "postsome";
    var index_name = "indexAB";

    indices[i]["indexAB"];             // ok, returns object on correct iteration
    indices[i][index_name];            // undefined
    if ("indexAB" in indices[i]) {
      indices[i].indexAB[0][doc_id]     // ok, returns undefined or keywords
      indices[i][index_name][0][doc_id] // undefined 
    }
}

index_name undefined因為之前的行引發錯誤

doc._id = "postname" // this causes an error

只需使用簡單的字符串

doc = "postname"

暫無
暫無

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

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