Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

is there a better way to merge array of objects in Javascript?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

My approach

I use reduce for the incoming data array, to walk over every item in the array and return a new array.
In my reduce function I check, if there is an item with the current invoice_id and client_id. If not, I will create it
Then I push a new item with the item_id, qty and price

{
  "use strict";
  
  const data = [
  {
    "invoice_id": 1,
    "item_id": 23,
    "client_id": 2,
    "price": 3000.00,
    "qty": 4
  },
  {
    "invoice_id": 1,
    "item_id": 45,
    "client_id": 2,
    "price": 8000.00,
    "qty": 1
  },
  {
    "invoice_id": 1,
    "item_id": 56,
    "client_id": 2,
    "price": 10000.00,
    "qty": 1
  },
]
  const parsedData = data.reduce((carry, item) => {
    let temp = carry.find(e => e.invoice?.invoice_id == item.invoice_id && e.client?.client_id == item.client_id);
    if (temp === undefined) {
      temp = carry[carry.push({}) - 1]
      temp.invoice = {invoice_id: item.invoice_id, items: []}
      temp.client = {client_id: item.client_id}
    }
    temp.invoice.items.push({item_id: item.item_id, price: item.price, qty: item.qty})
    return carry
  }, [])
  
  console.log(parsedData)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...