通过JavaScript的数组创建对象 [英] Javascript create Object by array

查看:188
本文介绍了通过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/

这篇关于通过JavaScript的数组创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆