Trying to update an element within a JSON object with a new value (text/object/array). I have a swap function that takes in the JSON object, an array with indexes to retrieve the element, and the value to replace it with. Currently using eval, which some consider "evil." Is there a better way to achieve this without eval or is eval acceptable in this scenario? It must be dynamic as the array may change. Also, important to note that the array parameter is programmatically created.
// Example array: ["cluster", "2", "segment", "0", "node", "3"]
JsonManager.prototype.swap = function(json, array, val){
var statement = "json";
for (var i = 0; i < array.length; i++) {
if(!isNumeric(array[i]))
{
statement += "[\"" + array[i] + "\"]";
} else {
statement += "[" + array[i] + "]"
}
}
statement += " = val";
eval(statement);
};
Example JSON Object:
var customers = {
"cluster": [{
"clusterid": "cluster1.1",
"color": "blue",
// More JSON data here...
}]
};
Test method:
JsonManager.prototype.init = function(){
var clause = new Clause("nodeid", "node4.4");
var indexes = this.search(customers, clause);
this.swap(customers, indexes.reverse(), {"name": "kevin"});
var test = customers["cluster"][2]["segment"][0]["node"][3];
var breakPoint = "breakpoint";
};
Solution further commented:
JsonManager.prototype.swap = function(obj, path, value) {
// Recursively traverse the object
function descend(obj, path) {
if (path.length == 0) {
return obj;
}
return descend(obj[path[0]], path.slice(1));
}
var node = descend(obj, path.slice(0, -1));
node[path[path.length - 1]] = value;
};