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

时间:2014-08-23 16:48:41

标签: javascript arrays

我有以下数组:

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": []
        }
    }
]

一种树状结构。但我没有得到正确的解决方案。我尝试的所有内容都以有线foreach结束,很快就无法调试。到目前为止,我所做的最好的是简单的reduce函数,但是如何将split('.')实现到此?我需要一些递归吗?

我现在最好的:

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

(我知道它并不多,但它很重要。但我认为reduce是一个很好的开始方式)

1 个答案:

答案 0 :(得分:1)

我将从路径构建一个树,最后添加中间'包含'数组

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);