Javascript 如何从嵌套数据创建VictoryPie
在我的React本机应用程序中,我以以下形式从我的存储访问数据:Javascript 如何从嵌套数据创建VictoryPie,javascript,reactjs,react-native,victory-charts,Javascript,Reactjs,React Native,Victory Charts,在我的React本机应用程序中,我以以下形式从我的存储访问数据: Array [ Checkout { "date": 2020-12-27T13:24:08.734Z, "id": "Sun Dec 27 2020 08:24:08 GMT-0500 (EST)", "items": Array [ Object { "productBrand&qu
Array [
Checkout {
"date": 2020-12-27T13:24:08.734Z,
"id": "Sun Dec 27 2020 08:24:08 GMT-0500 (EST)",
"items": Array [
Object {
"productBrand": "Microsoft",
"productCategory": "Gaming",
"productId": "p1",
"productTitle": "Xbox",
"quantity": 2,
"x": 1.815,
},
Object {
"productBrand": "Apple",
"productCategory": "Computers",
"productId": "p2",
"productTitle": "MacBook Pro",
"quantity": 1,
"x": 1.905,
},
],
"total": 3.720,
},
Checkout {
"date": 2020-12-27T13:24:47.790Z,
"id": "Sun Dec 27 2020 08:24:47 GMT-0500 (EST)",
"items": Array [
Object {
"productBrand": "Apple",
"productCategory": "Computers",
"productId": "p2",
"productTitle": "MacBook Pro",
"quantity": 1,
"x": 1.905,
},
],
"total": 1.905,
},
]
我试图使用VictoryPie
创建一个饼图,该饼图显示productBrand
通过所有对象的x
之和加权。在这个例子中,我需要一个饼图来显示微软和苹果,分别加权1.815和2*1.905=3.81。有没有办法不用编写单独的函数来计算这些总和?我希望饼图在每次向存储添加新数据时自动更新
我尝试了这个方法,其中history
是一个包含上述数组的变量,但没有生成饼图
<VictoryPie data={history} x={(data) => data.items.productBrand} y={(data) => data.items.x} />
data.items.productBrand}y={(data)=>data.items.x}/>
请参见我的工作示例:
像这样:
x="productBrand"
y={(data) => data.x * data.quantity}
对于任何试图执行类似操作的人,我最终通过使用
useSelector
hook中的嵌套For循环来提取所需的数据:
const allBrands = useSelector(state => {
let allData = {};
for (const key1 in state.history.history) {
for (const key2 in state.history.history[key1].items) {
if (allData.hasOwnProperty(state.history.history[key1].items[key2].productBrand)) {
allData[state.history.history[key1].items[key2].productBrand] += state.history.history[key1].items[key2].x;
} else {
allData[state.history.history[key1].items[key2].productBrand] = state.history.history[key1].items[key2].x;
}
}
};
let dataArray = [];
for (const prop in allData) {
dataArray.push({ brand: prop, total: allData[prop] })
}
return dataArray
});
将
所有品牌
传递给VictoryPie
数据道具,生成了正确的饼图。感谢您的回复-不幸的是,这在React Native中不起作用,也不会绘制饼图(它只显示相互重叠的类别标签)。我将代码复制到react本机沙盒中,它确实显示了一个饼图:。查看我对图像的更新回答好的,我看到了-这在您使用的数组格式下有效,但这与我使用的格式不同(请参见原始示例),那么该格式是什么?我看起来不熟悉。你不能只使用JSON吗?这是我商店中数据的格式-一个签出对象的数组,每个对象都有一个项字段,其中包含一个对象数组,其中包含饼图所需的数据。理想情况下,我可以直接从存储中提取这些数据