2013-04-28 193 views
0

我需要在javascript中獲取/設置嵌套對象,我寫了下面的setter,並且正在工作,我需要獲取幫助: 可以說我有以下對象,我想要做一些事情像Javascript設置訪問嵌套對象

var prop = get(object, ['complexObj', 'prop1']); 
set(object, ['complexObj', 'prop1'], 'newValue'); 
var object = { 
    complexObj: { 
     'prop1': 'A' 
     'prop2': 'B'}, 
    'prop3': 'C' 
}; 

// helper function 
var read = function(obj, prop) 
{ 
    if ((obj != null ? obj[prop] : void 0) == null) 
    { 
     return; 
    } 
    return obj[prop]; 
}; 
// The following methods allow contextManager data to be accessed either via array of property name parts like ['complexObj', 'subObj', 'subProp1'] 
var get = function (props) { 
    var current = properties; 
    var val; 
    for (var i = 0; i < props.length; i++) { 
     if (val = read(current, props[i])) { 
      current = val; 
     } else { 
      return ''; 
     } 
    } 
    return current; 
}; 

我徘徊,如果有一種方法可以做到這一點使用jQuery/lodash或另一個庫,對象內部的,而不是循環? 另外我需要一點幫助。

+2

你能不能簡單地縮進你的代碼?如果您需要,請使用http://jsbeautifier.org。 – 2013-04-28 15:57:27

+0

請問您可以縮進嗎?並更清楚地描述一下這個應該做什麼? – Ryan 2013-04-28 15:57:31

+3

爲什麼你不能只做'object.complexObj.prop1 =「newvalue」'? – Bart 2013-04-28 16:00:37

回答

0

嘗試

var object = { 
    complexObj: { 
     'prop1': 'A', 
     'prop2': 'B' 
    }, 
    'prop3': 'C' 
}; 

// helper function 
var read = function(obj, prop) { 
    return obj ? obj[prop] : undefined; 
}; 
// The following methods allow contextManager data to be accessed either via array of property name parts like ['complexObj', 'subObj', 'subProp1'] 
var get = function (properties, props) { 
    var current = properties; 
    var val; 
    for (var i = 0; i < props.length; i++) { 
     if (val = read(current, props[i])) { 
      current = val; 
     } else { 
      return undefined; 
     } 
    } 
    return current; 
}; 
console.log(get(object, ['complexObj', 'prop1'])); 
//set(object, ['complexObj', 'prop1'], 'newValue'); 
console.log(get(object, ['complexObj', 'prop1'])); 

演示:Fiddle

有像你這樣的一些錯誤,我們叫get它被定義之前,你必須通過objectget方法的第一個參數

+0

你可能應該返回'undefined'而不是'''' – 2013-04-28 16:11:07

+0

@ gion_13是的可能 – 2013-04-28 16:12:20

0
// get a property 
var get = function(obj, accessor) { 
    for (var i = 0, len = accessor.length; i < len; i++) { 
     if (!obj) return ""; 
     obj = obj[accessor[i]]; 
    } 

    return obj; 
}; 

// set a property 
var set = function(obj, accessor, value) { 
    for (var i = 0, len = accessor.length - 1; i < len; i++) { 
     if (!obj) obj = {}; 
     obj = obj[accessor[i]] = obj[accessor[i]] || {}; 
    } 

    obj[accessor[i]] = value; 
}; 

// example 
var object = { 
    a: 2, 
    b: { 
     c: 1 
    } 
}; 

get(object, ["b", "c"]); // 1 
set(object, ["d"], 3); // { a: 2, b: { c: 1 }, d: 3 } 
set(object, ["e", "f"], 4); // { ..., e: { f: 4 } } 

/* 
object == { 
    a: 2, 
    b: { 
     c: 1 
    }, 
    d: 3, 
    e: { 
     f: 4 
    } 
} 
*/ 

此代碼在設置不存在的屬性時會自動創建新對象。