具有数组值的对象成树

时间:2019-04-12 20:58:43

标签: javascript json tree

我有一个对象数组,其中每个对象都有一个值数组。数据结构不是理想的,但这是我访问它的唯一方法。我正在尝试将此结构转换为树形结构,以便构建一个D3缩进式可折叠表。

我尝试修改一些以前找到的答案,但尚未成功。这是我正在研究的当前JSFiddle的链接。

http://jsfiddle.net/COLTstreet/fsve7w2L/25/

这是数据如何传给我的一个小例子。

{
  "data": [
    {
      "items": [
        "All Other",
        "4C FOODS CORP"
      ],
      "hints": {
        "index": 0
      }
    },
    {
      "items": [
        "All Other",
        "PBNA"
      ],
      "hints": {
        "index": 14
      }
    },
    {
      "items": [
        "All Other",
        "PRIVATE LABEL"
      ],
      "hints": {
        "index": 15
      }
    },
    {
      "items": [
        "Base Water",
        "CCNA"
      ],
      "hints": {
        "index": 18
      }
    },
    {
      "items": [
        "Base Water",
        "CRYSTAL GEYSER"
      ],
      "hints": {
        "index": 19
      }
    }
  ]
}

我需要这样的代码才能完成:

[
  {
    "Category": "All Other",
    "children": [
      {
        "name": "4C FOODS CORP"
      },
      {
        "name": "PBNA"
      },
      {
        "name": "PRIVATE LABEL"
      }
    ]
  },
  {
    "Category": "Base Water",
    "children": [
      {
        "name": "CCNA"
      },
      {
        "name": "CRYSTAL GEYSER"
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:0)

一种解决方案是首先将Array.reduce()destructuring结合使用,以生成object用于按类别对元素进行分组,然后在第二步中使用Array.map()生成的对象entries以获得所需的输出:

const input = {
  "data": [
    {"items": ["All Other", "4C FOODS CORP"], "hints": {"index": 0}},
    {"items": ["All Other", "PBNA"], "hints": {"index": 14}},
    {"items": ["All Other", "PRIVATE LABEL"], "hints": {"index": 15}},
    {"items": ["Base Water", "CCNA"], "hints": {"index": 18}},
    {"items": ["Base Water", "CRYSTAL GEYSER"], "hints": {"index": 19}}
  ]
};

// Group by the category.
let res = input.data.reduce((acc, {items: [cat, val]}) =>
{
    acc[cat] = acc[cat] || [];
    acc[cat].push({name: val});
    return acc;
}, {});

// Generate desired output structure.
res = Object.entries(res).map(([k, v]) => ({category: k, children: v}));

console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}