2013-02-02 55 views
1

可能重複:
Accessing nested JavaScript objects with string key如何從Javascript中的參數訪問對象中的對象?

我具備的功能

function _get(name) { 
return plugin._optionsObj[name] !== undefined ? 
    plugin._optionsObj[name] : plugin._defaults[name]; 
} 

我希望能有我的_defaults對象的內部對象,但後來我不不知道如何檢索它們,但只使用一組方括號。

plugin._defaults = { 
    val1: 1, 
    val2: 2, 
    obj1: { 
     someVal: 3 
    } 
} 

是否有可能從我上面的功能訪問 'someVal'?我嘗試傳遞'obj1.someVal'作爲參數,但它不起作用。想法?

編輯:我找到了一個解決方案,我把它公佈在下面作爲答案。我寫了一個非常漂亮的小函數,通過字符串來檢查嵌套值,並且我不必爲了實現而更改功能。我希望這可以幫助任何處於類似情況的人。

+0

return plugin._optionsObj [name]!== undefined? plugin._optionsObj [name]:plugin._defaults [obj1] [someVal];不起作用? – lelloman

+1

看到這個要點:https://gist.github.com/3208381#file __。deep.js ...如果你使用Underscore,你只需將路徑(例如'obj1.someVal')作爲一個字符串傳遞,並且它遍歷該對象圖找到嵌套值。 –

+0

我期待着看看是否有辦法解決這個問題,而不改變我的功能或實現它。 – Klik

回答

0

我發現這個問題的解決方案,至少一個將容納自己,我想情況下,它可以幫助別人解決這個問題分享。我最大的困難是,我不知道嵌套值的深度,所以我想找到一個解決方案,可以爲深層嵌套對象工作,而不需要重新設計任何東西。

/* Retrieve the nested object value by using a string. 
    The string should be formatted by separating the properties with a period. 
    @param obj    object to pass to the function 
      propertyStr  string containing properties separated by periods 
    @return nested object value. Note: may also return an object */ 

function _nestedObjVal(obj, propertyStr) { 
var properties = propertyStr.split('.'); 
if (properties.length > 1) { 
    var otherProperties = propertyStr.slice(properties[0].length+1); //separate the other properties 
     return _nestedObjVal(obj[properties[0]], otherProperties); //continue until there are no more periods in the string 
} else { 
    return obj[propertyStr]; 
} 
} 


function _get(name) { 
    if (name.indexOf('.') !== -1) { 
    //name contains nested object 
     var userDefined = _nestedObjVal(plugin._optionsObj, name); 
     return userDefined !== undefined ? userDefined : _nestedObjVal(plugin._defaults, name); 
    } else { 
     return plugin._optionsObj[name] !== undefined ? 
     plugin._optionsObj[name] : plugin._defaults[name]; 
    } 
} 
-1

要檢索_defaults對象內部的對象,您需要改進您的_get函數。

例如,您可以將一個字符串數組(每個字符串表示一個私有名稱)傳遞給_get以允許訪問深度嵌套的對象。

+0

la spariamo a casaccio? – lelloman

1

我懷疑你不會總是有一個一級嵌套的對象來訪問,所以更簡單的方法是使用一個函數來遍歷一個基於字符串路徑的對象。 Here的編碼爲Underscore的混合編碼。然後你可以使用它像這樣:

_.deep(plugin._defaults, 'obj1.someVal'); 

This thread也有一些非下劃線的替代品。

+1

我最終寫了自己的功能,但謝謝你;你的答案非常有用。 – Klik

+0

太棒了,很高興你明白了。不要忘記在這裏發佈您的解決方案。 –

0

傳遞多個參數,並遍歷arguments對象。

function _get(/* name1, name2, namen */) { 
    var item = plugin._optionsObj, 
     defItem = plugin._defaults; 

    for (var i = 0; i < arguments.length; i++) { 
     item = item[arguments[i]]; 
     defItem = defItem[arguments[i]]; 

     if (item == null || defItem == null) 
      break; 
    } 
    return item == null ? defItem : item; 
} 

var opt = _get("obj1", "someVal") 
相關問題