无法正确地将Javascript数组转换为对象

时间:2011-05-04 00:06:54

标签: javascript

我整天都在努力解决这个问题。我觉得它是超级可解的,我不知道我哪里出错了。每次我发布这篇文章时,我觉得我想出了一个不会最终起作用的不同解决方案。

我希望做到以下几点:

var someObj = {};

// @param key - string - in the form of "foo-bar-baz" or "foo-bar". 
// (i won't know the number of segments ahead of time.)
// @param value - string - standard, don't need to act on it

function buildObject( key, value ) {

  var allKeys = key.split("-");

  // do stuff here to build someObj

}

基本上,密钥将始终采用key-key-key的格式,我想构建someObj[key1][key2][key3] = value

This JSFiddle包含一个较长的示例,其中包含我想要离开的数据结构的示例布局。

非常感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:2)

var someObj = {};

// @param key - string - in the form of "foo-bar-baz" or "foo-bar". 
// (i won't know the number of segments ahead of time.)
// @param value - string - standard, don't need to act on it
function buildObject( key, value ) {

  var allKeys = key.split("-");
  var container, i, n;
  for (container = someObj, i = 0, n = allKeys.length; i < n - 1; ++i) {
    var keyPart = allKeys[i];
    container = Object.hasOwnProperty.call(container, keyPart)
        ? container[keyPart] : (container[keyPart] = {});
  }
  container[allKeys[n - 1]] = value;
}

答案 1 :(得分:0)

在我看到迈克的回答之前,我想出了http://jsfiddle.net/XAn4p/。我只是以另一种方式张贴。

var newObj = function ()
    {};
newObj.prototype = 
    {
        addToObject: function (keys, value)
        {
            var keySplit = keys.split("-",2);
            if (keySplit.length  > 1)
            {
                if(this[keySplit[0]] == null)
                {
                   this[keySplit[0]] = new newObj();
                }
                var newKeys = keys.substr(keySplit[0].length +1);
                this[keySplit[0]].addToObject(newKeys, value);
            }
            else
            {
               this[keySplit[0]] = value 
            }
        }
    };

var obj = new newObj();