[英]How To Sum Values And Push To Matching Object In Vue
所以我試圖創建一個計算屬性,它將創建一個新的對象數組
我的問題是如何將與某個值匹配的值的數量相加,然后將該值推送到匹配對象中?
我需要推送的值是count:
。 我想算匹配來自一個單獨的數組調用每個工作流對象中的每個狀態值對象的數量engagements
。
我創建了一個 Jsfiddle點擊這里
數組在計算后應該是這樣的
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}
]
},
]
任何幫助將不勝感激或指出可以幫助我解決此問題的方向! 謝謝
您需要在狀態上使用Array#reduce來創建一個新的狀態數組(以避免改變原始狀態),然后在每次迭代中通過參與度對Array#filter進行計數,並計算與workflow_id
和status
匹配的status
。
const workflows = [{ id: 1, workflow: 'bookeeping', statuses: [{ status: 'Received' }, { status: 'Prepare' }, { status: 'Review' }, { status: 'Complete' }, ] }, { id: 2, workflow: 'payroll', statuses: [{ status: 'Received' }, { status: 'Scan' }, { status: 'Enter Data' }, { status: 'Review' }, { status: 'Complete' }, ] }, { id: 3, workflow: 'tax preparation', statuses: [{ status: 'Received' }, { status: 'Scan' }, { status: 'Prep' }, { status: 'Review' }, { status: 'Complete' }, ] }, ]; const engagements = [{ engagement: '1040', workflow_id: 1, status: 'Received' }, { engagement: '1040', workflow_id: 1, status: 'Received' }, { engagement: '1040', workflow_id: 1, status: 'Review' }, { engagement: '1040', workflow_id: 2, status: 'Review' }, { engagement: '1040', workflow_id: 2, status: 'Complete' }, { engagement: '1040', workflow_id: 2, status: 'Complete' }, { engagement: '1040', workflow_id: 3, status: 'Prep' }, { engagement: '1040', workflow_id: 3, status: 'Prep' }, { engagement: '1040', workflow_id: 2, status: 'Enter Data' }, { engagement: '1040', workflow_id: 2, status: 'Enter Data' }, { engagement: '1040', workflow_id: 2, status: 'Enter Data' }, { engagement: '1040', workflow_id: 1, status: 'Prepare' }, { engagement: '1040', workflow_id: 1, status: 'Prepare' }, ]; const res = workflows.map(({statuses, id}) => ({ workflow_id: id, statuses: statuses.reduce((acc, cur) => { const count = engagements.filter(({workflow_id, status}) => workflow_id === id && status === cur.status).length; if(count === 0) return acc; acc.push({status: cur.status, count}); return acc; }, []) })) console.log(res);
獲取代碼並對其進行分析:)
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.