Last active
December 15, 2015 22:09
-
-
Save fengdi/5330459 to your computer and use it in GitHub Desktop.
根据路径对一个json对象设置值 忽略异常
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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