2013-10-04 52 views
1

我需要這個陣列型possibleOptions的對象與用於cdOption字段某個字段值,以訪問一個元素:在對象數組訪問字段值以JavaScript

[Object { cdOption="OPT001", description="Description 1", type="STRING"}, 
Object { cdOption="OPT002", description="Description 2", type="STRING"}, 
Object { cdOption="OPT003", description="Description 3", type="STRING"}] 

字段值我正在尋找因爲它是從數組中的antoher對象中提取的,所以我在$ .each循環中使用alreay。 我可以避免進入另一個循環以便循環possibleOptions對象並查找指定的字段值嗎?

我試過 possibleOptions[option.cdOpzione]但它不起作用,有沒有辦法做到這一點?我知道我錯過了一些東西。

當前$。每個代碼:

$.each(oldOptions, function(key, option) {  
    $.each(possibleOptions, function(key, possibleOption) { 

     if (option.cdOption === possibleOptions.cdOption) { 
      console.log(option.cdOption); 
      console.log(possibleOption.description); 
     } 
    }); 
}); 
+0

您似乎有一個對象數組,因此您需要首先查詢對象的索引 – tikider

+0

您可以發佈您當前的'.each'代碼嗎? – tymeJV

回答

3

在一個通用的方法,你不能避免額外的週期。根據您的情況,可能有特定的解決方案。

解決方案1 ​​

你可以避開它,如果你調整你的數據,有possibleOptions與作爲關鍵字在cdOption值,並與描述和類型的值對象的對象。

例子:

var possibleOptions = { 
    'OPT001' : { description:"Description 1", type:"STRING" }, 
    'OPT002' : { description:"Description 2", type:"STRING" }, 
    'OPT003' : { description:"Description 3", type:"STRING" } 
}; 

var val = 'OPT002'; 
console.log(possibleOptions[val]); 

解決方案2

另一件事如果cdOption的形式總是OPT-指數 - 其中-index-是1+數組中的索引,你可以做是解析你正在尋找的值,提取-index-,parseInt並減去一個值。

實施例:

var val = 'OPT002'; 
var index = parseInt(val.substring(3))-1; 
console.log(possibleOptions[index]); 

演示兩種:http://jsbin.com/opojozE/1/edit

+0

謝謝。我可以使用第二種解決方案,但我認爲爲了完全確定我會使用額外的週期。我現在每個週期有3次,這有多糟糕? –

+1

如果沒有什麼選擇,你就沒有那麼多麻煩了。最簡單的方法是使用Array.prototype.filter,在@Paul Roub的答案中提到。它仍然遍歷數組,但代碼更易於閱讀,並且作爲本地函數,它有更多的機會被JS引擎優化。 – Tibos

1

Array.filter可以返回匹配的一個條件的元件的陣列。例如如果你想找到cdOption == "OPT002"對象(或對象),你可以說:

var matches = possibleOptions.filter(
    function(element) { 
     return ("OPT002" == element.cdOption); 
    } 
); 

matches將包含:

[ 
    { cdOption="OPT002", description="Description 2", type="STRING"} 
] 

如果你只是在尋找一個匹配:

var myOption = (matches.length > 0) ? matches[0] : null; 

如果您需要支持缺少Array.filter的舊版瀏覽器,請參閱MDN中的Array filter method以瞭解添加方法。