通过JavaScript的数组创建对象

问题描述:

我尝试与最后的关键值创建一个对象。我只是用键和值的Array,但不知道怎么会可能创造无JavaScript中使用引用的对象。

I try to create an object with a value for the last key. I just have an Array with the keys and the value but dont know how it will be possible to create an object without use references in javascript.

据我所知心不是一种方法,使用JavaScript创建一个变量的引用。

As far as I know there isnt a way to create a reference of a variable in javascript.

这是我有:

var value = 'test';
var keys = ['this', 'is', 'a', 'test'];

这是我想要的:

myObject: {
   this : {
     is: {
       a : {
         test : 'test'
       }
     }
   }
}

任何想法如何,我可以在JavaScript中这样做的最好方法是什么?

Any idea how i can do this the best way in JavaScript ?

这个怎么样?

keys.reduceRight(function(p, c) { var o = {}; o[c] = p; return o; }, value);

给我

{
    this: {
        is: {
            a: {
                test: "Test"
            }
        }
    }
}

请参阅Array.prototype.reduceRight() - 填充工具如果你需要IE< = 8支持

See Array.prototype.reduceRight() - Polyfill if you need IE <= 8 support.

的jsfiddle演示在这里 - http://jsfiddle.net/89Sx3/

jsFiddle demo here - http://jsfiddle.net/89Sx3/