The target object
The path identifying the location of the final key value
The value to set
let theValue = { };
setValueByKey(theValue, "Hello.Darkness.my", "old");
// Resulting Object: { Hello: { Darkness: { my: "old" } } }
setValueByKey(theValue, "friend", "I've");
// Resulting Object: { Hello: { Darkness: { my: "old" } }, friend: "I've" }
setValueByKey(theValue, "come.to.see", "you");
// Resulting Object: { Hello: { Darkness: { my: "old" } }, friend: "I've", come: { to : { see: "you" } } }
Set the named value on the target object where the path may be presented by a string which contains "." characters to separate the nested objects of the heirarchy / path to the value.
For safety, this helper blocks setting any path that includes unsafe keys (
__proto__,constructor, orprototype) and will also stop if the traversal reaches an unsafe target such as a built-in prototype object, without writing the final value. A missing (nullorundefined) value of the path is replaced by a new object, as is (since 0.20.0) an inherited function (eg. thehasOwnPropertyof an object or a method of a class), which is added as an own property of the target, so the path sets the target's own properties rather than changing an inherited (eg. built-in) function, eg."hasOwnProperty.call"sets the target's ownhasOwnPropertyto{ call: value }. Any objects which were added for the path are removed again when the value is not set (unless one was passed to an inherited setter). Since 0.20.0 the parts of the path are set with setValueByIter, so they have the same checks and the added objects are removed in the same way (an empty part, eg. the second part of"a..b", is still used as a key).