从属性数组创建动态嵌套对象 [英] Create a dynamic nested object from array of properties

查看:21
本文介绍了从属性数组创建动态嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来像一个简单的任务,但我不太明白:我有一个数组:

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?

推荐答案

你可以使用 reduce:

You could use reduce:

var array = ['opt1','sub1','subsub1','subsubsub1'];
var object = {};
array.reduce(function(o, s) { return o[s] = {}; }, object);
console.log(object);

但这仅在 ECMAScript 5.1 中引入,因此在某些较旧的浏览器中将不支持.如果你想要旧浏览器支持的东西,你可以使用上面 MDN 文章中描述的 polyfill 技术,或者一个简单的 for 循环,像这样:

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 array = ['opt1','sub1','subsub1','subsubsub1'];
var object = {}, o = object;
for(var i = 0; i < array.length; i++) {
    o = o[array[i]] = {};
}
console.log(object);

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

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