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

时间:2017-01-20 21:33:04

标签: javascript

使用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
  } 
]

3 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

let categoryLessonCount = lessons.reduce(function(acc, lesson) {
  let found = false
  for (const item of acc) {
    if (item.title === lesson.category) {
      item.count++
      found = true
    }
  }

  if (!found) {
    acc.push({
      title: lesson.category,
      count: 1
    })
  }

  return acc
}, [])

你的主要问题是你在累积一个对象但是期待一个数组(注意reduce的最后一个参数)。

答案 1 :(得分:1)

你已经得到了你想要的东西,只需把它变成一个数组



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)




答案 2 :(得分:1)

使用Object.keysArray.prototype.map函数的简短解决方案:

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

let counts = Object.keys(categoryLessonCount).map(
  (k) => ({title: k, count: categoryLessonCount[k]})
)

console.log(counts);