javascript - 将对象数组转换为分层数据结构
问题描述
我有一个对象数组,我想将其转换为不同的数组。原始数组中的每个对象都有一个类别键,我希望最终结果按类别对对象进行分组。我正在尝试使用 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
解决方案
您可以使用减少功能:
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
推荐阅读
- mongodb - 在 Golang 中使用 mongo-driver/mongo 的 FindOne 问题
- c# - 无法使用.netcore从天蓝色总线中的两个不同队列接收消息
- java - 在 Android Studio 中编码项目时出现渲染错误
- c# - Blazor 上 Microsoft 标识中的 AccountController 更改终结点
- postgresql - 在 Postgres 中 - 如何通过标识符/值从 JSONB 数组 (JSONB[]) 中删除元素
- sql - SQL查询(如果列包含某个值将其移动到另一列)
- windows - Docker 构建 - 无法计算缓存键:“/srv/app/www”未找到:未找到
- asp.net-mvc - WAF 仅针对一条记录阻止 JavaScript 文件
- selenium - Pythonanywhere | 硒铬
- c++ - 与数组的最后一个元素进行比较的是什么?