从性能的阵列创建一个动态的嵌套对象 [英] Create a dynamic nested object from array of properties
问题描述
这听起来像一个简单的任务,但我不能完全弄清楚:我有一个数组:
This sounds like a simple task, but I can't quite figure it out: I have an array :
var array = ['opt1','sub1','subsub1','subsubsub1']
这是我要生成以下对象:
From that I want to generate the following objects:
{
opt1:{
sub1:{
subsub1:{
subsubsub1:{}
}
}
}
}
我有办法做到这一点,使得串并使用eval,但我希望避免这种情况,任何想法?
I have a way to do it, making a string and using eval, but I'm looking to avoid that, any idea?
推荐答案
您可以使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\"><$c$c>reduce$c$c>:
var array = ['opt1','sub1','subsub1','subsubsub1'];
var object = {};
array.reduce(function(o, s) { return o[s] = {}; }, object);
但是,这只是在ECMAScript中引入5.1,这样就不会在一些旧的浏览器的支持。如果你想要的东西,将通过传统浏览器的支持,您可以使用MDN文章在上述填充工具技术,或者一个简单的为
-loop,像这样的:
But this was only introduced in ECMAScript 5.1, so it won't be supported in some older browsers. If you want something that will be supported by legacy browsers, you could use the polyfill technique described in the MDN article above, or a simple for
-loop, like this:
var object = {}, o = object;
for(var i = 0; i < array.length; i++) {
o = o[array[i]] = {};
}
这篇关于从性能的阵列创建一个动态的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!