Reduce array of objects by user_id and sum certain values

前端 未结 3 1158
旧时难觅i
旧时难觅i 2021-01-22 17:57

I have an array of objects that looks like this:

\"data\": [
{ \"workout_id\": 1, \"user_id\": 1, \"shotLocation\": 27, \"shotAttempts\": 20,\"shotsMade\": 19,          


        
3条回答
  •  旧时难觅i
    2021-01-22 18:21

    You can use Array.reduce, Object.values with ES6 destructuring and solve this in a concise manner:

    const data = [{ "workout_id": 1, "user_id": 1, "shotLocation": 27, "shotAttempts": 20, "shotsMade": 19, "id": 1 }, { "workout_id": 2, "user_id": 1, "shotLocation": 1, "shotAttempts": 10, "shotsMade": 9, "id": 2 }, { "workout_id": 2, "user_id": 1, "shotLocation": 10, "shotAttempts": 10, "shotsMade": 7, "id": 3 }, { "workout_id": 2, "user_id": 1, "shotLocation": 1, "shotAttempts": 30, "shotsMade": 29, "id": 4 }, { "workout_id": 3, "user_id": 5, "shotLocation": 1, "shotAttempts": 10, "shotsMade": 9, "id": 5 }, { "workout_id": 4, "user_id": 6, "shotLocation": 1, "shotAttempts": 30, "shotsMade": 15, "id": 6 }, { "workout_id": 4, "user_id": 6, "shotLocation": 2, "shotAttempts": 20, "shotsMade": 14, "id": 7 } ]
    
    const result = data.reduce((r,{workout_id, user_id, shotAttempts, shotsMade}) => {
     r[user_id] = r[user_id] || {id: workout_id, user_id, shotAttempts: 0, shotsMade: 0}
     r[user_id].shotAttempts += shotAttempts
     r[user_id].shotsMade += shotsMade
     return r
    }, {})
    
    console.log(Object.values(result))

提交回复
热议问题