var rooter = { user: { firstName: 'Billy', lastName: 'Moon', arbitrary: { namespace: { height: '1.4m' } } } };
var arb = "user.arbitrary.namespace.height";
fromPathString = function(pathString, targetObject){
pathString = pathString.split('.');
for(var i = 0; i < pathString.length; i++){
targetObject = (targetObject[pathString[i]])? targetObject[pathString[i]] : targetObject[pathString[i]] = {};
};
return targetObject
}
console.log(fromPathString(arb, rooter))
减少方法
arb.split('.').reduce(function(m, n){ return m[n] }, rooter)
因为.reduce
不是所有浏览器都兼容...
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) 3.0 (1.9) 9 10.5 4.0
用于 IE 9 及以下版本的 Shim...(来自 MDN)
只需在调用.reduce
任何数组之前放置...
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, opt_initialValue){
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError(
'Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index, value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
}
else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}