Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k 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 Reply

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...