オブジェクトの配列があり、それを別の配列に変換したいと思います。元の配列の各オブジェクトにはカテゴリキーがあり、最終結果でオブジェクトをカテゴリ別にグループ化したいと思います。これを行うために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をご覧ください。
reduce関数を使用し、最初にアイテムが配列にすでに存在するかどうかを確認します。存在する場合は、見つかったインデックスを使用して要素を見つけ、その子に追加します。存在しない場合は、最初のアイテムを子配列に追加します。
const input = [{
category: "film",
title: "toy story"
},
{
category: "film",
title: "harry potter"
},
{
category: "tv",
title: "seinfeld"
}
]
const result = input.reduce((acc, x) => {
const index = acc.findIndex(y => y.category === x.category)
if (index >= 0) {
acc[index].children.push({
title: x.title
})
} else {
acc = [...acc, {
category: x.category,
children: [{
title: x.title
}]
}]
}
return acc;
}, []);
console.log(result)
子の重複がない場合:
const result = input.reduce((acc, x) => {
const index = acc.findIndex(y => y.category === x.category)
const indexTitle = acc[index] && acc[index].children.findIndex(y => y.title === x.title)
if (index >= 0) {
if (indexTitle !== 0) {
acc[index].children.push({
title: x.title
})
}
} else {
acc = [...acc, {
category: x.category,
children: [{
title: x.title
}]
}]
}
return acc;
}, []);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加