Skip to content

Instantly share code, notes, and snippets.

@fengdi
Last active December 15, 2015 22:09
Show Gist options
  • Save fengdi/5330459 to your computer and use it in GitHub Desktop.
Save fengdi/5330459 to your computer and use it in GitHub Desktop.
根据路径对一个json对象设置值 忽略异常
function setValueByPath(obj, path, value){
var temp, k, re = obj;
if(!obj || (typeof obj!="object" && typeof obj!="function"))
return obj;
(path+"").replace(/([^.:]+)([.:])?/g, function(m, n, sign){
temp = obj;
k = n;
obj = obj[n] = (obj!=void 0 && (typeof obj=="object" || typeof obj=="function") && n in obj) ? obj[n] : sign ==":" ? [] : {};
});
if(k && temp){
temp[k] = value;
}
return re;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment