2014-10-20 66 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' } }