2014-10-20 64 views
0

我試圖創建能夠設置對象的某個值的函數,具有屬性的「路徑」:node.js中設置屬性從字符串屬性名

reflectionSet = function(obj, propString, value) { 
    var current = obj; 
    var splitted = propString.split('.'); 
    splitted.forEach(function(k) { 
     current = current[k]; 
    }) 
    current = value; 
} 
var test = { 
    a: { 
     s: 'asd', 
     g: 'asasdasdd' 
    } 
}; 

reflectionSet(test, 'a.g', "otherValue"); 

,它應該成爲:

{ 
    a: { 
     s: 'asd', 
     g: 'otherValue' 
    } 
} 

不幸的是,這並不在所有的工作..謝謝

+0

這是因爲JavaScript是 「傳遞的價值」。這意味着當你收集變量g時,你不會改變Object中的值。只是從Object中收集的值。 [Here](http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value)是一個更詳實的解釋 – magnudae 2014-10-20 14:05:43

回答

1

您可以使用拆分基於.,然後使用Array.prototype.reduce性質,得到了在NER對象的大部分,並更新它像這樣

function reflectionSet(obj, propString, value) { 
    return propString.split(".").reduce(function(result, part, index, array) { 
     if (index === array.length - 1) { 
      result[part] = value; 
      return obj; 
     } 
     return result[part]; 
    }, obj); 
} 

var test = { 
    a: { 
     s: 'asd', 
     g: 'asasdasdd' 
    } 
}; 

console.log(reflectionSet(test, 'a.g', "otherValue")); 

輸出

{ 
    a: { 
     s: 'asd', 
     g: 'otherValue' 
    } 
} 
+0

currentItam沒有設置 – rodi 2014-10-20 14:15:26

+0

@rodi糟糕,有一個錯字。我現在修好了。請檢查。 – thefourtheye 2014-10-20 14:17:59

1

你的函數的該修正版本應該這樣做。

reflectionSet = function(obj, prop, value) { 
    prop = prop.split('.'); 
    var root = obj, i; 
    for(i=0; i<prop.length; i++) { 
     if(typeof root[prop[i]] == 'undefined') root[prop[i]] = {}; 
     if(i === prop.length - 1) root[prop[i]] = value; 
     root = root[prop[i]]; 
    } 
    return obj; 
}; 

現在:

var test = { a: { s: 'asd', g: 'asasdasdd' } }; 
reflectionSet(test, 'a.g', "otherValue"); 

將返回{ a: { s: 'asd', g: 'otherValue' } }