4

我已经看到了很多相关的问题和谷歌结果,但似乎没有一个与我的问题相匹配。

我得到一个字符串“header.h2”,我想将它连接到' var objects'。所以我想要objects.header.h2(其中包含更多的哈希数据)。

但是,我不想使用 eval() 或经常建议buttons[]的,原因很明显buttons[header.h2] 不起作用,我需要buttons[header][h2].

那么我怎样才能保持对象符号,或者在最坏的情况下,解决我的问题呢?

4

2 回答 2

8

只是一个可能的方式的快速草图:

您的数据

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-13T09:09:54.437 回答
3

我将创建一个“填充”方法,该方法根据给定的点符号字符串创建对象:

var populate = function(obj, str) {
  var ss=str.split(/\./), len=ss.length, i, o=obj;
  for (i=0; i<len; i++) {
    if (!o[ss[i]]) { o[ss[i]] = {}; }
    o = o[ss[i]];
  }
  return obj;
};

var objects = populate({}, 'header.h2');
objects.header.h2; // => Object {}
populate(objects, 'foo.bar.gah.zip');
objects.foo.bar.gah.zip; // => Object {}

需要测试,但应该让你更接近你的目标。

于 2011-04-13T09:26:54.067 回答