gpt4 book ai didi

javascript - 根据属性和 javascript 中的计数按对象数组分组

转载 作者:行者123 更新时间:2023-12-01 23:56:58 25 4
gpt4 key购买 nike

我有一个对象数组 temp。我想根据对象的属性进行分组。例如,要对性别进行分组,并计算其计数。

const temp = [
{
properties: {
"id":1234,
"gender": 'male',
"status": "Active"
}
},
{
properties: {
"id":1456,
"gender": 'male',
"status": "Not Active"
}
},
{
properties: {
"id":1377,
"gender": 'female',
"status": "Active"
}
},
{
properties: {
"id":8799,
"gender": 'female',
"status": "Active"
}
}
];

需要分组的props可以像这样传递

groupFunc = (data) => {
const metrics = data
for (i = 0; i < temp.length; i++) {
data.map( el =>
temp[i].properties.el ? grouped.push([{"key": el, "value": temp[i].properties.el,"count":1}])
:
null
)
console.log(temp[i].properties)
}
};
groupFunc(["gender","status"]);

分组累加后的最终结果应该是

grouped = [
[
{
"key": "gender",
"value": "male",
"count": 2
},
{
"key": "gender",
"value": "female",
"count": 2
}
],
[
{
"key": "status",
"value": "Active",
"count": 3
},
{
"key": "status",
"value": "Not Active",
"count": 1
},
]

]

最佳答案

const temp = [{properties:{"id":1234,"gender":'male',"status":"Active"}},{properties:{"id":1456,"gender":'male',"status":"Not Active"}},{properties:{"id":1377,"gender":'female',"status":"Active"}},{properties:{"id":8799,"gender":'female',"status":"Active"}}];

const groupByKeys = (data, keys) => {
let finalResult = keys.map(key => {
return Object.values(data.reduce((result, obj)=>{
let objKey = obj["properties"][key]
result[objKey] = result[objKey] || {key: key, count: 0, value: objKey};
result[objKey].count += 1;
return result
},{}))
})
return finalResult
}

console.log(groupByKeys(temp, ["gender", "status"]))

关于javascript - 根据属性和 javascript 中的计数按对象数组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62635607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com