【发布时间】:2021-09-16 17:28:27
【问题描述】:
我正在尝试准备要与 amCharts 库一起使用的数据。最终的数据结构需要这样格式化:
data = [{
name: "First",
total: 190,
children: [
{
name: "A1",
value: 100
},
{
name: "A2",
value: 60
},
{
name: "A3",
value: 30
},
],
name: "Second",
total: 150,
children: [
{
name: "B1",
value: 100
},
{
name: "B2",
value: 30
},
{
name: "B3",
value: 20
},
]
}]
我准备的数据如下所示:
const data = {
'Corporate Investors': {
total: 7, // total number of 'Corporate Investors', not the sum total of 'stages'
stages: {
Seed: 7,
'Series A': 7,
'Series B': 7,
'Series C': 7,
'Series D': 7
}
},
'Angel investor': {
total: 11,
stages: {
Seed: 10,
'Series A': 10,
'Series B': 11,
'Series C': 11,
'Series D': 9
}...
我已经制作了一个辅助函数来将此对象转换为 amCharts 需要的数组类型(从此处找到的其中一个演示中修改一个:https://www.amcharts.com/demos/drill-down-treemap/
function processData(data) {
const treeData = [];
let typeData = {};
// loops through the outer 'Angel investor' type-keys
for (const key of Object.keys(data)) {
typeData = { name: key, total: data[key].total, children: [] };
// loops over the 'stages' for each of the outer keys
for (const stage of Object.keys(data[key].stages)) {
typeData.children.push({ name: stage, count: data[key].stages[stage] });
}
console.log('typeData pre-push: ', typeData);
console.log('treeData pre-push: ', treeData);
treeData.push(typeData);
console.log('treeData post-push: ', treeData);
}
return treeData;
}
有几个嵌套循环,可能很难遵循,但它确实成功地将我的原始对象处理成 amCharts 之后的数组格式,除非它被推入 treeData 我似乎丢失了 CHILDREN 值.这是来自 VS Code 的 console.logs 的输出:
我已经通过将数据拉入我的 react 组件并在那里记录它来确认这一点,并且 children 数组完全为空。
当我推入数据时,我的数据会发生什么情况,导致它失去我所有的孩子值?
【问题讨论】:
-
你怎么称呼
processData工作 -
尝试在
for循环中初始化typeData -
我把它缩短了一点,但它似乎在这个小提琴中工作正常:jsfiddle.net/yak613/1zqxp0yj 这不是预期的行为吗?
标签: javascript arrays function object