這是我的解決方案:
用途:
警報(CommonUt.GetValueProperty({「馬姆mal「:{」Dog「:{」Value「:5}}},」Mammal.Dog.Value「)); ({「Mammal」:{「Dog」:{「Value」:5}}},「Mammal.Dog.Value」,6);
變種CommonUt = {
/***
* Check if the propertyName is present in obj.
* PropertyName can be a string with 'dot' separator for deepest property
* Ex: ContainProperty(json, "Mammal.Dog");
* @param obj The object where search the property
* @param propertyName {string} the name of the property
*/
ContainProperty : function(obj, propertyName) {
if (!IsNotNullObject(obj)) {
return false
}
if (!IsNotEmptyString(propertyName)) {
throw new Error("I cannot check for an empty property name.");
}
if (propertyName.indexOf('.') === -1) {
return (propertyName in obj);
}
var refObj = obj;
var founded = true;
$.each(propertyName.split('.'), function(i, item) {
if (!(item in refObj)) {
founded = false;
return false;
}
refObj = refObj[item];
});
return founded;
},
/***
* Get the value of a property (or sub-property)
* WARN: if the value of the property is 'value-type' any changes will not be propagated!
* @param obj {object}
* @param propertyName {string} Property name. For 'deep' property split by dots: Mammal.Dog
*/
GetValueProperty : function(obj, propertyName) {
if (!CommonUt.ContainProperty(obj, propertyName)) {
throw new Error("I cannot retrieve the property reference if the property doesen't exists!");
}
if (propertyName.indexOf('.') === -1) {
return obj[propertyName];
}
var refObj = obj;
$.each(propertyName.split('.'), function(i, item) {
refObj = refObj[item];
});
return refObj;
},
/***
* To threat with value properties, use this
* @param obj
* @param propertyName
* @param value
*/
SetValueProperty : function(obj, propertyName, value) {
if (!CommonUt.ContainProperty(obj, propertyName)) {
throw new Error("I cannot retrieve the property reference if the property doesen't exists!");
}
if (propertyName.indexOf('.') === -1) {
obj[propertyName] = value;
return;
}
var refObj = obj;
var slices = propertyName.split('.');
for (var i = 0; i < (slices.length - 1); i++) {
refObj = refObj[slices[i]];
}
refObj[slices[slices.length-1]] = value;
}
};
只是爲了清楚起見:在這裏沒有JSON,JSON只是一個對象的字符串表示;你在這裏處理普通的JavaScript對象,用對象文字符號(≠[JSON](http://json.org))編寫。 – 2011-01-21 13:54:21
Tnx Marcel Korpel:我的錯誤:你是對的! – PadovaBoy 2011-01-21 15:25:59