当我执行console.log(variable1)时,我有一个看起来像这样的变量。
0: {node01: "site05", amount: 1010}
1: {node01: "site02", amount: 1200}
2: {node01: "site08", amount: 880}
3: {node01: "site04", amount: 870}
4: {node01: "site01", amount: 650}
5: {node01: "site06", amount: 1370}
6: {node01: "site07", amount: 100}
7: {node01: "site09", amount: 210}
8: {node01: "site10", amount: 340}
另一个在console.log(variable2)中看起来像这样的变量:
0: {node02: "site08", amount: 100}
1: {node02: "site02", amount: 200}
2: {node02: "site03", amount: 1050}
3: {node02: "site07", amount: 1300}
4: {node02: "site09", amount: 850}
5: {node02: "site10", amount: 890}
6: {node02: "site04", amount: 640}
7: {node02: "site06", amount: 290}
8: {node02: "site01", amount: 50}
9: {node02: "site05", amount: 200}
10: {node02: "site11", amount: 1060}
我想根据节点值添加两个变量的数量例如,“ node01”:“ site05”的数量为:1010,而“ node02”:“ site05”的数量为:200结果变量应具有“ node”:“ site05”,数量:1210。另外,variable1中不存在“ site11”。因此它应该只具有值“ node”:“ site11” amount:1060->仅来自变量2
我尝试使用两个嵌套的for循环,但这只会导致节点在一个变量中可用。我不确定如何将它们全部映射。另外,有没有只使用d3js而不使用js固有的for循环的解决方案?据我了解,D3还有其他循环方法
提前感谢
我认为您可能需要准备数据,然后将合并结果发送到D3。例如:
const list1 = [
{node01: "site05", amount: 1010},
{node01: "site02", amount: 1200},
{node01: "site08", amount: 880},
{node01: "site04", amount: 870},
{node01: "site01", amount: 650},
{node01: "site06", amount: 1370},
{node01: "site07", amount: 100},
{node01: "site09", amount: 210},
{node01: "site10", amount: 340},
];
const list2 = [
{node02: "site08", amount: 100},
{node02: "site02", amount: 200},
{node02: "site03", amount: 1050},
{node02: "site07", amount: 1300},
{node02: "site09", amount: 850},
{node02: "site10", amount: 890},
{node02: "site04", amount: 640},
{node02: "site06", amount: 290},
{node02: "site01", amount: 50},
{node02: "site05", amount: 200},
{node02: "site11", amount: 1060},
];
const combinedList = [
...list1,
...list2,
];
const output = Object.values(combinedList.reduce((a, c) => {
const node = Object.values(c).find(v => typeof v === 'string');
a[node] = a[node] || {node, amount: 0};
a[node].amount += c.amount;
return a;
}, {}));
console.log(output);