This is a challenge that I'm facing in solving a problem. I want my users to be able to do the following:
- Point to any key of an object with any depth using a string representation of the "path";
- Ensure that each step of the "path" exists; and
- Implement CRUD-like functionality.
I am able to validate each key, but I am struggling on how to use the path without resorting to using the eval()
function, which is not safe when dealing with user input. Here is where I currently stand:
const SEP = "/" //this value is dynamically set by the server,
MyObjInterface = function() {
this.params = {};
this.response = {};
//some initialization code here...and now for the question.
this.updateOb= function(path, value ) {
path = path.replace('\\' + DS,"$DIRECTORY_SEPARATOR").split(DS);
for (var i = 0; i < path.length; i++) {
path[i].replace("$DIRECTORY_SEPARATOR",DS);
}
if (typeof(path) != "object" || path.length < 3) {
throw "Could not create rset representation: path is either incorrectly formatted or incomplete."
}
var invalidPath = false;
var searchContext = path[0] === "params" ? this.params : this.response;
for (var i = 1; i < path.length - 1; i++) {
if (invalidPath) { throw "No key found in rset at provided path: [" + path[i] + "]."; }
if (i === path.length - 1) {
searchContext[path[1]] = value;
return true;
}
if (path[i] in searchContext) {
searchContext = searchContext[path[i]];
} else {
invalidPath = true;
}
}
}
};