Monday 15 June 2015

javascript - node.js set property from string property name -



javascript - node.js set property from string property name -

i trying create function able set value of object, having "path" of property:

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");

and should become:

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

unfortunately doesn't work @ all.. thanks

you can utilize split properties based on . , using array.prototype.reduce, inner part of object , update this

function reflectionset(obj, propstring, value) { homecoming propstring.split(".").reduce(function(result, part, index, array) { if (index === array.length - 1) { result[part] = value; homecoming obj; } homecoming result[part]; }, obj); } var test = { a: { s: 'asd', g: 'asasdasdd' } }; console.log(reflectionset(test, 'a.g', "othervalue"));

output

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

javascript node.js object

No comments:

Post a Comment