我正在尝试根据其中一个键将一些项目合并到 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/