Search code examples
javascriptarrayslodash

Pushing objects in an array to a different array by key


I am trying to push an array of objects to another existing array of objects.

Example:

var invoices = [ 
{ 
  InvoiceId: 2,
  Contact: 'Jim',
  InvoiceNumber: '3',
  LineItems: [] 
},
{ 
  InvoiceId: 1002,
  Contact: 'Peter',
  InvoiceNumber: '4' },
  LineItems: [] 
}];


var invoiceLines = [ 
{ Id: 1003,
 InvoiceId: 2 },
 Amount: 1000,
{ Id: 1004,
 InvoiceId: 2,
 Amount: 1000,
{ Id: 1006,
 InvoiceId: 1002,
 Amount: 3000,}];

So I am trying to take each object in the invoiceLines array, and push it to invoices.Lineitems if InvoiceId matches. So it would look like this:

var result= [ 
{ 
 InvoiceId: 2,
 Contact: 'Jim',
 InvoiceNumber: '3',
 LineItems: [{ 
   Id: 1003,
   InvoiceId: 1002,
   Amount: 1000},{ 
   Id: 1004,
   InvoiceId: 1002,
   Amount: 1000}] 
},
{ 
 InvoiceId: 1002,
 Contact: 'Peter',
 InvoiceNumber: '4' },
 LineItems: [{
   Id: 1006,
   InvoiceId: 1002,
   Amount: 3000}] 
}];

I have tried the following:

var result = _({})
 .merge(
  _(flattenedinvoiceLines).groupBy("InvoiceId").value(),
  _(invoices).groupBy("Id").value())
 .values()
 .flatten()
 .value();
}

How ever this just pushes into the invoices array, not invoice.LineItems.


Solution

  • You can walk through invoices and then find all matches in invoiceLines by validating the InvoiceId is the same. below sample code

    var invoices = [ 
    { 
      InvoiceId: 2,
      Contact: 'Jim',
      InvoiceNumber: '3',
      LineItems: []
    },
    { 
      InvoiceId: 1002,
      Contact: 'Peter',
      InvoiceNumber: '4',
      LineItems: [] 
    }
    ];
    
    var invoiceLines = [
    { Id: 1003,
     InvoiceId: 2,
     Amount: 1000 
    },
    { Id: 1004,
     InvoiceId: 2,
     Amount: 1000,
     },
    { Id: 1006,
     InvoiceId: 1002,
     Amount: 3000
     }
     ];
     
      
     
    const result = invoices.map(invoice => {
      invoice.LineItems = invoiceLines.filter((line) => line.InvoiceId === invoice.InvoiceId)
      return invoice;
    })
     console.log(result)