如何使用交叉过滤驱动的 dc.js 图表创建子项目的饼图?

问题描述 投票:0回答:1

假设我有一份客户列表及其订单:

const customers = [
  { id: 1, orders: [{ products: ["apple", "banana"] }, { products: ["apple"] }] },
  { id: 2, orders: [{ products: ["strawberry"] }] },
  { id: 3, orders: [{ products: ["apple"] }, { products: ["strawberry"] }] },
  { id: 4, orders: [] }
]

我希望看到一个饼图,其中显示每个可用产品的切片。过滤时,我想点击“苹果”并按在任何时间点订购苹果的客户进行过滤。

我目前可以渲染饼图,但它以切片形式显示产品的所有可能组合。

意思是,我的饼图有一个

apple, banana
strawberry
apple, strawberry
none
的切片。

这不是我想要的。我通过创建维度来做到这一点:

const dimension = crossfilter.dimension((customer: Customer) => {

    const productList = customer.orders.flatMap(x => x.products)
    const products = new Set<string>(productList);
    const result = [...products ];
    if (result.length === 0) return "none";

    return result;
})

const group = dimension.group();

过滤行为正常工作,但饼图切片无法以这种方式持续。

javascript dc.js crossfilter
1个回答
0
投票

这似乎是因为您正在返回一个数组,即

result
变量。 您可以在单个列表中提取产品:

const customers = [
  { id: 1, orders: [{ products: ["apple", "banana"] }, { products: ["apple"] }] },
  { id: 2, orders: [{ products: ["strawberry"] }] },
  { id: 3, orders: [{ products: ["apple"] }, { products: ["strawberry"] }] },
  { id: 4, orders: [] }
];

const allProducts = [...customers.reduce((s, a) => {
  const customerProducts = a.orders.flatMap(o => o.products);
  customerProducts.forEach(p => s.add(p));
  if (customerProducts.length === 0)
    s.add("none");
  return s;
}, new Set())];

console.log(allProducts);

© www.soinside.com 2019 - 2024. All rights reserved.