简体   繁体   中英

compare two arrays of Objects in JavaScript and if true save new items to MongoDB

Good Afternoon, I am trying to compare two arrays of objects, each object contains an id. One array comes from Stripe the other from my DB. If the ID's match then returns true and if not return false. The idea is that if there is an id that does not match then it will return false and run another function that does the updating. Right now I am using forEach(), but I was using two for loops for both arrays, but it was not working properly. My function returns false even though there are elements in both arrays that match. Below is my code with both methods and also the implementation.

 function findCommoneID(stripeInvoice, DBInvoices) { var isSame = false; stripeInvoice.forEach((StripeElement) => { DBInvoices.forEach((DBElement) => { if(StripeElement.id === DBElement.id) { isSame = true } }) }); return isSame; } // Implementation app.get('/store-update-invoices', async (req, res) => { const stripe = require('stripe')(`${process.env.REACT_APP_Stripe_Live}`); const invoice = await stripe.invoices.list().catch((e) => {console.log(e)}); const invoices = app.get('Invoices'); if(findCommoneID(invoice.data, invoices)) { console.log('Ids exist'); return; } else { console.log('ids dont exist') // DBInvoices( invoice, invoices); <-- function that runs update } });

Try to make these changes to you findCommoneID function

function findCommoneID(stripeInvoice, DBInvoices) {
  var isSame = true;
  stripeInvoice.forEach((StripeElement) => {
    DBInvoices.forEach((DBElement) => {
        if(StripeElement.id !== DBElement.id) {
          isSame = false
          break;
        } 
    })
  });
  return isSame;
}

You algorithm is flawed currently. You are checking each item in Stripe against each item in DB. Meaning unless both arrays are [X][X][X]...[X], then your check will fail.

What you want is:

Stripe's First element == DB's first element
Stripe's Second element == DB's second element
...
Stripe's last element == DB's last element

Suggested pseudocode:

if Stripe.length != DB.length
    return false
for (int i = 0; i < Stripe.length; i++) 
   if Stripe[i] != DB[i]
        return false

return true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM