我试图弄清楚是否有办法使用array.map()
我有两个位置列表(WOL,SYD,MEL等),其中一个列表中每个位置都有所有设备作为子设备的站点总数,另一个列表中有错误的设备。 / p>
我需要找到每个网站的错误设备百分比,以及每个网站的设备总数。
有没有办法可以使用uniqueSitesCount.map(...)来做到这一点?我整个周末一直在查看文档,并在询问之前试图找出答案,但到目前为止都失败了。
uniqueSitesCountNotOk
- 只有设备处于错误状态的位置数组添加到'设备'子阵列:
[ { site: 'CBR',
devices: [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'MEL',
devices: [ [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'SYD', devices: [] },
{ site: 'WOL', devices: [] } ]
uniqueSitesCount
- 包含所有对象的位置数组
[ { site: 'CBR',
devices: [ [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'MEL',
devices: [ [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'SYD', devices: [ [Object], [Object], [Object], [Object], [Object] ] },
{ site: 'WOL', devices: [ [Object], [Object], [Object], [Object], [Object] ] } ]
功能:
为了清晰起见,编辑:uniqueSitesCount[i].count
到uniqueSitesCount[i].devices.length
var getSiteErrorPercentage = function(uniqueSitesCount, uniqueSitesCountNotOk) {
for (var i = 0; i < uniqueSitesCount.length; i++) {
if (uniqueSitesCountNotOk[i].devices.length > 0) {
console.log(`${uniqueSitesCount[i].site} - ${(uniqueSitesCountNotOk[i].devices.length / uniqueSitesCount[i].devices.length* 100).toFixed(2)}%`)
} else {
console.log(uniqueSitesCount[i].site + ' - 0%')
}
}
}
答案 0 :(得分:1)
我会考虑快速循环uniqueSitesCount
来制作一个直接将网站映射到对象计数的对象。类似的东西:
var uniqueSitesCount = [
{ site: 'CBR', devices: [[],[],[],[],[],[],[],[],[],[],[] ] },
{ site: 'MEL', devices: [[],[],[],[],[] ] },
{ site: 'SYD', devices: [[],[],[],[],[] ] },
{ site: 'WOL', devices: [[],[],[],[],[] ] }
]
var counts = uniqueSitesCount.reduce((acc, cur) => {
acc[cur.site] = cur.devices.length
return acc
}, {})
计数看起来像:
{ CBR: 11, MEL: 5, SYD: 5, WOL: 5 }
通过它,您可以映射错误并创建一个包含以下百分比的数组:
var uniqueSitesCount = [
{ site: 'CBR', devices: [[],[],[],[],[],[],[],[],[],[],[] ] },
{ site: 'MEL', devices: [[],[],[],[],[] ] },
{ site: 'SYD', devices: [[],[],[],[],[] ] },
{ site: 'WOL', devices: [[],[],[],[],[] ] }
]
var uniqueSitesCountNotOk = [
{ site: 'CBR', devices: [ [], [], [], [], [], [] ] },
{ site: 'MEL', devices: [ [], [], [], [], [] ] },
{ site: 'SYD', devices: [] },
{ site: 'WOL', devices: [] }
]
var counts = uniqueSitesCount.reduce((acc, cur) => {
acc[cur.site] = cur.devices.length
return acc
}, {})
var percents = uniqueSitesCountNotOk.map(item => {
var n = item.devices.length / counts[item.site] * 100
return {site:item.site, count: n}
})
console.log(percents)
&#13;
或者,您可以避开计数对象,但是每次都必须搜索uniqueSitesCount
对象:
var percents = uniqueSitesCountNotOk.map(item => {
var site = uniqueSitesCount.find(i => i.site === item.site )
var n = item.devices.length / site.devices.length * 100
return {site:item.site, count: n}
})