javascript - 取消嵌套和减少javascript中的数据结构

标签 javascript d3.js bubble-chart

我有一个关于 Wine 的数据集。对于每个 Wine 标签,我都有几个信息,如原产国、酿造的葡萄、是白 Wine 还是红 Wine 、评级等。我从 csv 中获取这些数据。最终,对于我正在构建的可视化,我需要一个类型的数据:Grape |白色或红色 |计数。我能够得到这样的数据:

count: 1
grape: (3) ["Pinot Noir", "Malbec", "Garnacha"]
type: "Red wine"

count: 1
grape: ["Pinot Noir"]
type: "Red wine"

count: 1
grape: ["Pinot Noir"]
type: "Red wine" 

对于我数据集中的每个 Wine 标签。但是,我需要这样的数据:

count: 1
grape: "Pinot Noir"
type: "Red wine"

count: 1
grape: "Malbec"
type: "Red wine"

count: 1
grape: "Garnacha"
type: "Red wine"

count: 1
grape: "Pinot Noir"
type: "Red wine"

count: 1
grape: "Pinot Noir"
type: "Red wine"

以便稍后我可以简化为:

count: 3
grape: "Pinot Noir"
type: "Red wine"

count: 1
grape: "Malbec"
type: "Red wine"

count: 1
grape: "Garnacha"
type: "Red wine"

是否可以通过 javascript 做到这一点?

最佳答案

你可以试试下面的代码。

var data = [
  { count: 1, grape: ["Pinot Noir", "Malbec", "Garnacha"], type: "Red wine" },
  { count: 1, grape: ["Pinot Noir"], type: "Red wine" },
  { count: 1, grape: ["Pinot Noir"], type: "Red wine" }
];

var newData = [];

data.forEach(item => {
  item.grape.forEach(g => {
    var addedItem = newData.find(f => f.type == item.type && f.grape == g);
    if (addedItem) {
      addedItem.count += +item.count;
    } else {
      newData.push({
        count: +item.count,
        grape: g,
        type: item.type
      });
    }
  });
});
console.log('Result: ', newData);

编辑:可以通过以下方式更改代码以获得更好的性能。

var data = [
  { count: 1, grape: ["Pinot Noir", "Malbec", "Garnacha"], type: "Red wine" },
  { count: 1, grape: ["Pinot Noir"], type: "Red wine" },
  { count: 1, grape: ["Pinot Noir"], type: "Red wine" }
];

var counts = {};
data.forEach(item => {
  item.grape.forEach(g => {
    if (counts[item.type]) {
      if (counts[item.type][g]) {
        counts[item.type][g] += +item.count;
      } else {
        counts[item.type][g] = +item.count;
      }
    } else {
      counts[item.type] = { [g]: item.count };
    }
  });
});

var newData = [];
Object.keys(counts).forEach(type => {
  Object.keys(counts[type]).forEach(grape => {
    newData.push({ count: counts[type][grape], grape: grape, type: type });
  });
});
console.log('Result: ', newData);

关于javascript - 取消嵌套和减少javascript中的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155959/

相关文章:

javascript - 如何从 jQuery 更改为 JavaScript

javascript - d3.js json结构添加数据

javascript - 无法让标签与 D3-tile 投影一起使用

javascript - 如何通过多个条件 Mongoose 在数组中仅查找一个对象

php - 如何为 Javascript array() 使用准备 PHP 变量?

javascript - 如何在 D3 中使用交叉过滤器进行过滤

r - 使用 ggplot2 绘制气泡图

javascript - 使用 d3.geo.mercator 的气泡图

javascript - Redux.js - 可以手动创建一个函数来监听 Javascript 中的另一个函数吗?