Skip to content

Instantly share code, notes, and snippets.

@harmoniemand
Last active March 16, 2016 14:30
Show Gist options
  • Save harmoniemand/f70639b7cf3b5518d69c to your computer and use it in GitHub Desktop.
Save harmoniemand/f70639b7cf3b5518d69c to your computer and use it in GitHub Desktop.
/**
* Update a json node of an object
* Could create needed nodes, if path not exists
* @param {object} obj - the object that should be updated
* @param {string} path - the path of the node that should be updated
* @param value - the new value for the node
* @param {bool} createNodes - if true, the missing nodes will be created - if false, a error will be thrown if any of the nodes in the path is missing
*/
var updateJson = function (obj, path, value, createNodes) {
if (obj === undefined) { obj = {}; }
if (path === undefined) { path = ''; }
if (createNodes === undefined) { createNodes = false; }
if (path.indexOf('.') > -1) {
// not a the node you are looking for.
if (obj[path.substr(0, path.indexOf('.'))] === undefined) {
// the node you are looking for does not exists.
if (createNodes === false) { return new Error("path not valid - missing node " + path); }
obj[path.substr(0, path.indexOf('.'))] = {};
}
var nPath = path.substr(path.indexOf('.') + 1);
var nObj = obj[path.substr(0, path.indexOf('.'))];
obj[path.substr(0, path.indexOf('.'))] = updateJson(nObj, nPath, value, createNodes);
return obj;
} else {
obj[path] = value;
return obj;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment