在 javascript 中的对象嵌套数组中查找百分比值



在数组的嵌套对象中,百分比值应该映射到具有更大计数的对象。 数据对象有两个数组"distinctCount">"groupByAndCount"。区别计数包含一个对象。

{
"key": "total",
"value": 7
}

基于对象应分组的键名的"groupByAndCount",应获取计数最高的值并除以"distinctCount"中获得的值,然后乘以100以获得百分比 例: 在键"marital_status">中,"单身">值的计数">6">最高,而计数"1">较低的值"已婚">

{
"key": "marital_status",
"value": "Single",
"count": 6/7*100 = 85.7%
}

我是reduce函数的初学者,我认为使用百分比获取约简对象需要化简器函数

const result = data.groupByAndCount.map(e => e.reduce((a, { key, value, count }) => 
(a['key'] = key,a['value'] = value,a['count'] = count, a), {}));
const data = {
distinctCount : [
{
"key": "total",
"value": 7
},
{
"key": "member_total",
"value": 7
}
]
,
groupByAndCount : [
[
{
"key": "marital_status",
"value": "Married",
"count": 1
},
{
"key": "marital_status",
"value": "Single",
"count": 6
}
],
[
{
"key": "payment",
"value": "POST",
"count": 7
}
],
[
{
"key": "customer_code",
"value": "ABC",
"count": 1
},
{
"key": "customer_code",
"value": "DEF",
"count": 6
}
]
]
};

预期结果:

const result = {
distinctCount : [
{
"key": "total",
"value": 7
},
{
"key": "member_total",
"value": 7
}
]
,
groupByAndCount : [
[
{
"key": "marital_status",
"value": "Single",
"count": 85.71
}
],
[
{
"key": "payment",
"value": "POST",
"count": 100
}
],
[
{
"key": "customer_code",
"value": "DEF",
"count": 85.71
}
]
]
};

首先,您的total count是唯一的,因此您可以将其取出变量以简化计算。您可以使用对对象数组(data.distinctCount(进行简单搜索来做到这一点。

function search(array, value){
for (var i=0; i < array.length; i++) {
if (array[i].key === value) { 
return array[i].value; 
}
}
}
const total_value = search(data.distinctCount, 'total');
Output:
7

其次,您希望仅具有每个数组的最大计数的对象(data.groupByAndCount内的数组(。

const maxGroupByAndCount = data.groupByAndCount.map(function(arr){
return [arr.sort((a,b)=>b.count-a.count)[0]];
});
Output:
[
[{key: "marital_status", value: "Single", count: 6}],
[{key: "payment", value: "POST", count: 7}],
[{key: "customer_code", value: "DEF", count: 6}]
]

现在,只需通过与total_value进行比较来转换每个计数的百分比;

maxGroupByAndCount.map(function(arr){
arr[0].count = (arr[0].count/ total_value) * 100;
});
console.log(maxGroupByAndCount);
Output:
[
[{key: "marital_status", value: "Single", count: 85.71428571428571}],
[{key: "payment", value: "POST", count: 100}],
[{key: "customer_code", value: "DEF", count: 85.71428571428571}]
]

现在,您可以执行对象分配以使其成为一个对象。

const result = { 
'distinctCount' : data.distinctCount, 
'groupByAndCount': maxGroupByAndCount
};

你绝对可以改进我的答案,使其更加优化。

最新更新