我有一个图片
const events: {
'12327ae260fe9431': {
eventType: 'DEVICE_LINK_ERR',
key: '12327ae260fe9431',
severity: 'ERROR',
timestamp: 1542199782975,
title: 'Link went down unexpectedly',
},
'62d29fab77bddd7': {
eventType: 'DEVICE_LINK_ERR',
key: '62d29fab77bddd7',
severity: 'ERROR',
timestamp: 1542199783055,
title: 'Link went down unexpectedly',
},
},
我要计算总体严重性并构造一个severityCounts
对象,像这样
severityCounts: {
CRITICAL: 0,
ERROR: 2,
INFO: 0,
WARNING: 0,
}
,我可以访问Lodash
。我应该怎么做?
答案 0 :(得分:2)
您可以使用Object.values()
生成所有值的数组,然后使用array#reduce
创建一个对象,每个对象的计数为severity
。
const events = { '12327ae260fe9431': { eventType: 'DEVICE_LINK_ERR', key: '12327ae260fe9431', severity: 'ERROR', timestamp: 1542199782975, title: 'Link went down unexpectedly', }, '62d29fab77bddd7': { eventType: 'DEVICE_LINK_ERR', key: '62d29fab77bddd7',severity: 'ERROR', timestamp: 1542199783055, title: 'Link went down unexpectedly', }, },
severityCounts = Object.values(events).reduce((r, {severity}) => {
r[severity] = ( r[severity] || 0 ) + 1;
return r;
},{ CRITICAL: 0, ERROR: 0, INFO: 0, WARNING: 0});
console.log(severityCounts);
答案 1 :(得分:2)
您可以按severity
对数据进行分组,获取长度并将所有信息分配给单个对象。
var data = { '12327ae260fe9431': { eventType: 'DEVICE_LINK_ERR', key: '12327ae260fe9431', severity: 'ERROR', timestamp: 1542199782975, title: 'Link went down unexpectedly' }, '62d29fab77bddd7': { eventType: 'DEVICE_LINK_ERR', key: '62d29fab77bddd7', severity: 'ERROR', timestamp: 1542199783055, title: 'Link went down unexpectedly' } },
result = _.assign(
{ CRITICAL: 0, ERROR: 0, INFO: 0, WARNING: 0 },
..._(data)
.values()
.groupBy('severity')
.map(({ length }, key) => ({ [key]: length }))
.value()
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
答案 2 :(得分:1)
在询问之前,请务必在OP中发布您的尝试,以便我们了解您的位置
您可以使用for .. of
和下面的增量计数器遍历对象。无需lodash
const events = {
'12327ae260fe9431': {
eventType: 'DEVICE_LINK_ERR',
key: '12327ae260fe9431',
severity: 'ERROR',
timestamp: 1542199782975,
title: 'Link went down unexpectedly',
},
'62d29fab77bddd7': {
eventType: 'DEVICE_LINK_ERR',
key: '62d29fab77bddd7',
severity: 'ERROR',
timestamp: 1542199783055,
title: 'Link went down unexpectedly',
},
'62d29fab77bddd71': {
eventType: 'DEVICE_LINK_ERR',
key: '62d29fab77bddd7',
severity: 'INFO',
timestamp: 1542199783055,
title: 'Link went down unexpectedly',
}
}
let severityCounts = { CRITICAL: 0, ERROR: 0, INFO: 0, WARNING: 0 }
for(let { severity } of Object.values(events)) {
severityCounts[severity] = severityCounts[severity] || 0
severityCounts[severity]++
}
console.log(severityCounts)