javascript - 如何将对象的值与 JavaScript 中的公共(public)键结合起来?

标签 javascript json highcharts underscore.js

我正在尝试根据其中一个键将一些项目合并到 JSON 数组中。我想按'metric'分组,然后我需要查看'rounded_counts'中的所有时间/值数据,如果时间相同,则需要将值加在一起。这是源数据:

let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 }, 
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

这里是 Highcharts 图形库所需的输出——注意这两个名为“已批准”的指标如何合并它们的值

可以使用下划线和/或 ES6 - 提前致谢!

let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]

最佳答案

这是我的两分钱。

const sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },

  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },

  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

function mergeDatas(currentObject, rounded_counts) {
  return rounded_counts.map(x => {
    if (currentObject.data.some(y => y[0] === Object.keys(x)[0])) {
      const miniArray = currentObject.data.find(y =>
      y[0] === Object.keys(x)[0]);

      miniArray[1] += x[Object.keys(x)[0]];

      return miniArray;
    }

    return x;
  })
}

const result = sourceData.reduce((tmp, x) => {
  if (tmp.some(t => t.name === x.metric)) {
    const currentObject = tmp.find(y => y.name === x.metric);

    mergeDatas(currentObject, x.rounded_counts);

    return tmp;
  }

  tmp.push({
    name: x.metric,
    data: x.rounded_counts.map(y => {
      const key = Object.keys(y)[0];

      return [key, y[key]];
    }),
  });

  return tmp;
}, []);

console.log(result);

关于javascript - 如何将对象的值与 JavaScript 中的公共(public)键结合起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47334253/

相关文章:

javascript - 为什么 onclick 在 JavaScript 中不起作用?

php - json_decode() 返回空问题

javascript - 带有 json 内容类型的 jquery ajax post 以 HTML 形式返回错误请求

JavaScript AddEventListener 异常

javascript - Angular Controller - 双向广播

javascript - 使用 Math.random() 和 .css 的 jQuery/JS 随机图像定位?

php - 即使数据库中不存在空值,JSON 响应中也会返回空值

javascript - 如何使用 Angular js在指令中给出点击事件?

javascript - Highcharts "Cannot read property ' toFront' 未定义”

javascript - 我们可以在 Highcharts 折线图中找到击穿点/击穿分析吗?