0
{
  "company": [
    { "region": [ "Europe", "Germany" ], "productLine": "Produce" },
    { "region": [ "Europe", "France" ], "productLine": "Produce" }
    ],
    "company2": [
    { "region": [ "Europe", "Germany" ], "productLine": "Produce" },
    {  "region": [ "Americas", "USA" ], "productLine": "Produce" }
    ]
}

有了这个 json 数据,我如何重建它,以便我将欧洲/美洲值作为主要(唯一)节点,而德国/法国作为它的子节点?company/company1 将是法国/德国的子子级。我似乎无法弄清楚如何在保持关系正确的同时构建数组。我本质上我需要反转节点树。

预期输出:

树形结构如下:

-Europe
   -France
      -Company
      -Company2

我还需要一个树插件的特殊结构:

var source = [ { label: "Europe", items: [
   {label: "France", items: [
      {label: "SuperShop", items: [
            {label: "Produce"}
         ]}
      ]
   }]
}]

我最终需要的是一个带有值对的对象数组:标签,项目。项目是一个包含子对象的对象。

4

1 回答 1

3

显然,我不知道您为什么需要新格式,但它似乎过于复杂。如果您正在查看一个大型数据集,那么您的速度会受到影响,因为在当前设置下,您将遍历新数组的每个元素以找到您正在查找的元素为了 ...

var inputs = {
  "company": [
    { "region": [ "Europe", "Germany" ], "productLine": "Produce" },
    { "region": [ "Europe", "France" ], "productLine": "Produce" }
    ],
    "company2": [
    { "region": [ "Europe", "Germany" ], "productLine": "Produce" },
    {  "region": [ "Americas", "USA" ], "productLine": "Produce" }
    ]
};

var converter = {};

// This new format requires a 2 step process to prevent it from being N^2
// So convert the input into a tree
//   Region
//     -> Country
//       -> Company
//         -> Array of Products
for(var company in inputs){
  for(var i = 0; i < inputs[company].length; i++){
    // Because the regions are an array of hashes it is simplest
    // to grab the value by using the previously gathered keys
    // and the key region
    var r = inputs[company][i]['region'];

    // Check if the region exists.  If not create it.
    if(!converter[r[0]]){
      converter[r[0]] = {};
    }
    // Check if the country exists.  If not create it.
    if(!converter[r[0]][r[1]]){
      converter[r[0]][r[1]] = {};
    }
    // Add the company to the array.
    if(!converter[r[0]][r[1]][company]){
      converter[r[0]][r[1]][company] = [];
    }
    converter[r[0]][r[1]][company].push(inputs[company][i]['productLine']);
  }
}

var outputs = [];

// Now walk converter and generate the desired object.
for( var region in converter){
  converted_region = {};
  converted_region["label"] = region;
  converted_region["items"] = [];
  for( var country in converter[region]){
    converted_country = {};
    converted_country["label"] = country;
    converted_country["items"] = [];
    for( var company in converter[region][country]){
      converted_company = {};
      converted_company["label"] = company;
      converted_company["items"] = [];
      for(var i = 0; i < converter[region][country][company].length; i++){
        converted_company["items"].push(converter[region][country][company][i]);
      }
      converted_country["items"].push(converted_company);
    }
    converted_region["items"].push(converted_country);
  }
  outputs.push(converted_region);
}
于 2013-04-21T18:42:22.270 回答