首页 > 解决方案 > 将对象数组转换为分层数据结构

问题描述

我有一个对象数组,我想将其转换为不同的数组。原始数组中的每个对象都有一个类别键,我希望最终结果按类别对对象进行分组。我正在尝试使用 reduce 方法来执行此操作,但无法理解我找到的示例。

原始数组:

[
  {category: "film", title: "toy story"}, 
  {category: "film", title:"harry potter"},
  {category: "tv", title:"seinfeld"}
]

期望的结果:

[
  {
    category: "film",
    children: [
      {title: "toy story"}, 
      {title: "harry potter"}
    ],
  }
  {
    category: "tv",
    children: [
      {title: 'seinfeld' }
    ]
  }
]

我正在尝试使用 d3 创建一些图形,并且数据需要按层次结构进行排序。更多关于这里,https://github.com/d3/d3-hierarchy/blob/v1.1.9/README.md#hierarchy

标签: javascriptarraysd3.js

解决方案


您可以使用减少功能

const arr = [
  {category: "film", title: "toy story"},
  {category: "film", title: "harry potter"},
  {category: "tv", title: "seinfeld"}
]

const arrByCategory = arr.reduce((acc, i) => {
  // Check if the category already exist in the new array
  const elIdx = acc.findIndex(_ => _.category === i.category);
  const elExist = elIdx > -1;

  if(elExist) {
    // If the category exist, we just add the title to the children list
    return acc[elIdx].children.push({title: i.title})

  } else {
    // If the category does not exist we create it and add the initial title in the children list
    return acc.concat({
      category: i.category,
      children: [{ title: i.title }]
    })
  }
},[])

为了让你更好地理解reduce函数,下面是一个简单的例子:

const array = [1, 3, 6, 2, 5]
const sum = array.reduce((acc, i) => {
  return acc + i;
}, 0)

console.log(sum) // 17


推荐阅读