Group by key an array

PHOTO EMBED

Wed Feb 23 2022 16:31:20 GMT+0000 (Coordinated Universal Time)

Saved by @ITAG #javascript #array #groupby

const refunds = [
  {
    request_amount_to_refund: "3000",
    entity_id: "1850231228424",
    is_zni: false
  },
  {
    request_amount_to_refund: "2000",
    entity_id: "1850231228422",
    is_zni: false
  },
  {
    request_amount_to_refund: "1000",
    entity_id: "1850231228422",
    is_zni: true
  },
  {
    request_amount_to_refund: "500",
    entity_id: "1850231228422",
    is_zni: true
  }
]
    
const refundsFormatted = Object.values(refunds.reduce((acc, curr) => {
  const valueId = `${curr.entity_id}-${curr.is_zni}`

  // Does value already exist ?
  const existingValue = acc[valueId]

  // Values to add
  const existingRequestAmount = parseInt(existingValue?.request_amount_to_refund ?? 0)
  const newRequestAmount = parseInt(curr?.request_amount_to_refund ?? 0)
  const quantity = existingValue?.quantity ? existingValue?.quantity + 1 : 1

  const newValue = {
    ...curr,
    request_amount_to_refund: existingRequestAmount + newRequestAmount,
    quantity: quantity
  }
  return ({
    ...acc,
    [valueId]: newValue,
  })
}, {}))

console.log(refundsFormatted)

/**
Output expected 

[
  {
    request_amount_to_refund: "3000",
    entity_id: "1850231228424",
    is_zni: false,
    quantity: 1
  },
  {
    request_amount_to_refund: "2000",
    entity_id: "1850231228422",
    is_zni: false,
    quantity: 1
  },
  {
    request_amount_to_refund: "1500",
    entity_id: "1850231228422",
    is_zni: true,
    quantity: 2
  }
]
*/
content_copyCOPY

Fusionne des objets qui respectent un même ID et une même conditions (ZNI)