简体   繁体   English

将数组转换为嵌套对象

[英]Convert array into nested object

Let's say I have the following array: ['product' , 'model', 'version'] 假设我有以下数组:['product','model','version']

And I would like to have an object such as: 我想要一个对象,例如:

{
    product: { 
        model: { 
            version: { 

            }
        }
     }
}

However, that array is dynamic so it could have 2, 3 or fewer more items. 但是,该数组是动态的,因此它可以包含2、3或更少的项目。 How can this be achieved in the most efficient way? 如何以最有效的方式实现这一目标?

Thanks 谢谢

Just turn it inside out and successively wrap an inner object into an outer object: 只需将其内部翻过来,然后将内部对象依次包装到外部对象中即可:

 const keys = ['product', 'model', 'version']; const result = keys.reverse().reduce((res, key) => ({[key]: res}), {}); // innermost value to start with ^^ console.log(result); 

If I understood request correctly, this code might do what you need: 如果我正确理解了请求,那么此代码可能会满足您的要求:

function convert(namesArray) {
  let result = {};
  let nestedObj = result;
  namesArray.forEach(name => {
    nestedObj[name] = {};
    nestedObj = nestedObj[name];
  });

  return result;
}


console.log(convert(['a', 'b', 'c']));

You can also do it with Array.prototype.reduceRight : 您也可以使用Array.prototype.reduceRight做到这一点:

 const result = ['product','model','version'].reduceRight((all, item) => ({[item]: all}), {}); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM