gpt4 book ai didi

javascript - 对特定属性具有相同值的元素进行计数,并将结果放入对象数组中

转载 作者:行者123 更新时间:2023-11-30 11:43:35 24 4
gpt4 key购买 nike

使用 Array.reduce ,我正在尝试计算对特定属性具有相同值的元素。我想将结果放入一个对象数组中,其中包含一个用于按属性分组的值的属性和另一个用于计数的属性。我怎样才能在 javascript 中轻松做到这一点?

const CATEGORY = {
STRATEGY: 'STRATEGY',
CONTENT: 'CONTENT',
ADVERTISING: 'ADVERTISING',
MEASURMENT: 'MEASURMENT'
}

const lessons = [
{
title: 'ohoho',
category: CATEGORY.STRATEGY
}, {
title: 'hihihi',
category: CATEGORY.CONTENT
}, {
title: 'hello',
category: CATEGORY.CONTENT
}
]

let categoryLessonCount = lessons.reduce(function (acc, lesson) {
acc[lesson.category] ? acc[lesson.category]++ : acc[lesson.category] = 1
return acc
}, {})
console.log(categoryLessonCount[CATEGORY.STRATEGY])
console.log(categoryLessonCount[CATEGORY.CONTENT])
实际 categoryLessonCount 值:

Object
{
STRATEGY: 1,
CONTENT: 2
}

想要的 categoryLessonCount 值:

Array
[
{
title: 'STRATEGY',
count: 1
}, {
title: 'CONTENT',
count: 2
}
]

最佳答案

你已经得到了你想要的只是将它转换成一个数组

const CATEGORY = {
STRATEGY: 'STRATEGY',
CONTENT: 'CONTENT',
ADVERTISING: 'ADVERTISING',
MEASURMENT: 'MEASURMENT'
}

const lessons = [{
title: 'ohoho',
category: CATEGORY.STRATEGY
}, {
title: 'hihihi',
category: CATEGORY.CONTENT
}, {
title: 'hello',
category: CATEGORY.CONTENT
}]

let count = lessons.reduce(function(acc, lesson) {
acc[lesson.category] ? acc[lesson.category] ++ : acc[lesson.category] = 1
return acc
}, {})

// transform count into what you want
let categoryLessonCount = [];
for (let cat in count) {
categoryLessonCount.push({
'title': cat,
'count': count[cat]
});
}

console.log(categoryLessonCount)

关于javascript - 对特定属性具有相同值的元素进行计数,并将结果放入对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41772685/

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