Javascript 在树对象中转换和分组字符串数组

Javascript 在树对象中转换和分组字符串数组,javascript,arrays,Javascript,Arrays,我有以下数组: var exampeInclude= [ "Product", "Group", "Product.Tax", "Product.ProductUnit", "Product.Variant.Original", "Product.Variant.Original.Tax", "Product.Variant.Original.ProductUnit" ]; 我需要从该数组中获取以下结构: [ { "Product": {

我有以下数组:

var exampeInclude= [
  "Product",
  "Group",
  "Product.Tax",
  "Product.ProductUnit",
  "Product.Variant.Original",
  "Product.Variant.Original.Tax",
  "Product.Variant.Original.ProductUnit"
];
我需要从该数组中获取以下结构:

 [
    {
        "Product": {
            "includes": [
                {
                    "Tax": {
                        "includes": []
                    }
                },
                {
                    "ProductUnit": {
                        "includes": []
                    }
                },
                {
                    "Variant": {
                        "includes": [
                            {
                                "Original": {
                                    "includes": [] //...
                                }
                            }
                        ]
                    }
                }
            ]
        }
    },
    {
        "Group": {
            "includes": []
        }
    }
]
一种树状结构。但我没有得到正确的解决方案。我尝试的一切都以wired foreach结束,很快就无法调试。到目前为止,我所拥有的最好的功能是一个简单的reduce函数,但是如何将
拆分('.')
实现到这个函数中呢?我需要一些递归吗

我现在拥有的最好的:

var hist = exampeInclude.reduce(function (prev, item) { 
  if( item in prev ) prev[item] ++; 
  else prev[item] = 1; 
  return prev;  
}, {});

(我知道这不算多,只是算数而已。但我认为
reduce
是一个很好的开始)

我会从路径构建一棵树,最后添加中间的“includes”数组

function buildFromPath(tree, pathVar){
  var a = pathVar.split('.'),
     parent = tree;
  for(var i = 0, max = a.length; i < max; i++){
     var n = a[i];
     if(!(n in parent))   parent[n] = {};
     parent = parent[n];
  }
}
var exampeInclude= [
  "Product",
  "Group",
  "Product.Tax",
  "Product.ProductUnit",
  "Product.Variant.Original",
  "Product.Variant.Original.Tax",
  "Product.Variant.Original.ProductUnit"
],
tree = {};
for(var i = 0, max = exampeInclude.length; i < max; i++){
   buildFromPath(tree, exampeInclude[i]);
}
// normally here you should have a tree structure
// like {Product:{Tax:{},ProductUnit:{},Variant:{Original:{Tax:{},ProductUnit:{}}}},Group:{}}
// then you parse the tree and add format with intermediates
function formatObj(obj){
   var res = [];
   for(var name in obj){
     var o = obj[name];
     res.push(o);
     o.includes = formatObj(o);
   }
   return res;
}
var res = formatObj(tree);
函数buildFromPath(树,路径变量){
var a=pathVar.split('.'),
父=树;
对于(变量i=0,max=a.length;i
这是非常具体的,可以用文字形式化您想要的内容:解析字符串路径数组,从路径构建树对象,但每个对象将包含一个包含子对象的“包含”子数组,是否准确?