如何在Vue中求和并推入匹配对象

时间:2018-11-11 18:57:59

标签: javascript arrays object vue.js

因此,我尝试创建一个计算属性,该属性将创建一个新的对象数组

我的问题是如何求和与某个值匹配的值的数量,然后将该值推入匹配的对象?

我需要推送的值为count:。我试图从称为engagements的单独数组中计算与每个工作流对象中的每个状态值匹配的对象数。

我创建了一个Jsfiddle Click Here

计算后的数组应该看起来像这样

var arr = [
  { workflow_id: 1, 
       statuses: [ 
                  { status: "Received", count: 3},
                  { status: "Review", count: 2},
                  { status: "complete", count: 4}
                ] 
  },
  { workflow_id: 2, 
       statuses: [ 
                  { status: "Received", count: 3},
                  { status: "Review", count: 1},
                  { status: "complete", count: 1}
                ] 
  },
  { workflow_id: 3, 
       statuses: [ 
                  { status: "Received", count: 3},
                  { status: "Data Entry", count: 2},
                  { status: "complete", count: 1}
                ] 
  },
]

任何帮助将不胜感激,或者指出可以帮助我解决此问题的方向!谢谢

2 个答案:

答案 0 :(得分:1)

您需要在状态上使用Array#reduce来创建新的状态数组(以避免对原始状态进行变异),然后在每次迭代中通过参与度对Array#filter进行计数并计算与{ {1}}和workflow_id

status

答案 1 :(得分:0)

获取代码并对其进行分析:)

function sumProps(arr) {
  const result = []
  for(const el of arr) {
    const obj = result.find(e => e.workflow_id === el.workflow_id)
    if (!obj) {
      result.push({
        workflow_id: el.workflow_id,
        statuses: [{
          status: el.status,
          count: 1
        }]
      })
      continue
    }
    const status = obj.statuses.find(s => s.status === el.status)
    if (!status) {
      obj.statuses.push({
        status: el.status,
        count: 1
      })
      continue
    }
    status.count += 1
  }
  return result
}