只是一种可能的方式速写:
您的数据:
var data = [
{foo: 1, bar: 2, foobar: [
'a', 'b', 'c'
]},
{foo: 1, bar: 2, foobar: [
'd', 'e', 'f'
]},
{foo: 1, bar: 2, foobar: [
'g', 'h', 'i'
]}
];
var accessor = '1.foobar.2';
使用辅助函数:
function helper(data, accessor) {
var keys = accessor.split('.'),
result = data;
while (keys.length > 0) {
var key = keys.shift();
if (typeof result[key] !== 'undefined') {
result = result[key];
}
else {
result = null;
break;
}
}
return result;
}
,或将其提供给所有对象 :(亲自,我不喜欢这个......)
Object.prototype.access = function (accessor) {
var keys = accessor.split('.'),
result = this;
while (keys.length > 0) {
var key = keys.shift();
if (typeof result[key] !== 'undefined') {
result = result[key];
}
else {
result = null;
break;
}
}
return result;
};
调试输出:
console.log(
helper(data, accessor), // will return 'f'
data.access(accessor) // will return 'f'
);
那么分裂点,然后遍历它们并将它们设置在多维数组中?看起来不错! – 2011-04-13 09:21:40