JSON: loop Invoice Items : add if InvoiceNo not exits, update value if it does, example included
-
29-06-2021 - |
سؤال
I'm trying to loop through a list of Invoices, and their Individual LineItem Values, and in the end have an Ojbect of [object Arrays] with an Invoice Number and the total value for all line items per Invoice.
var objInvoiceLineItem = function (strInvoiceNo,strValue) {
this.InvoiceNo= strInvoiceNo;
this.Value = strValue;
}
//
var objAllInvoices = [];
//
function AddValueTo_objAllInvoices(myInvoice){
//don't know how to look and see if the Invoice exists?
//jQuery.inArray?
//for (var i = 0; i < objAllInvoices.length - 1; i++)?
if exists (myInvoice.InvoiceNo) = false{
var newObjInvoiceItem=
new objInvoiceLineItem(myInvoice.InvoiceNo, myInvoice.Value);
objAllInvoices.push(newObjInvoiceItem)
}
else{
//need help here please
var obj = getobject;
objAllInvoices.obj.Value += myInvoice.Value;
}
}
//
var Invoice1A = new objInvoiceLineItem("Invoice1",20);
var Invoice1B = new objInvoiceLineItem("Invoice1",50);
var Invoice2A = new objInvoiceLineItem("Invoice2",30);
AddValueTo_objAllInvoices(Invoice1A);
AddValueTo_objAllInvoices(Invoice1B);
AddValueTo_objAllInvoices(Invoice2A);
المحلول
I think something like this will do what you want:
function AddValueTo_objAllInvoices(myInvoice)
{
for (var i = 0; i < objAllInvoices.length; i++)
{
if (objAllInvoices[i].InvoiceNo == myInvoice.InvoiceNo)
{
// invoice exists, update it and return
objAllInvoices[i].Value += myInvoice.Value;
return;
}
}
// if the invoice already existed, we would have returned in the loop
// so we wouldn't have ever gotten here, so the invoice must not exist.
// create it now:
var newObjInvoiceItem = new objInvoiceLineItem(myInvoice.Container, myInvoice.Value);
objAllInvoices.push(newObjInvoiceItem);
}
لا تنتمي إلى StackOverflow