Search code examples
javascriptarraysobject

How to check an array of objects against another one?


I have one array of objects with all items and their respective price like this:

var items = [
 {
  "id": "001",
  "name": "apple",
  "price": 500
},
{
  "id": "002",
  "name": "banana",
  "price": 700
},
{
  "id": "003",
  "name": "pear",
  "price": 200
 }
];

then I have a client's car like this:

var cart = [{
  "id": "001",
  "qty": 2
},
{
  "id": "002",
  "qty": 3
},
{
  "id": "003",
  "qty": 4
}
];

Client's credit is stored in a variable. I want to check the second array against the first one to get the total of the cart and make sure it won't exceed client's credit. I'm not sure how to do it though. I tried:

var mytotal=cart.map(d => {
 var total=0;
  items.forEach(rm => {
   total = total+(d.qty*rm.price);
  } return total; 
});

if(credit >= total) {//dosomething}

but it didn't work. What is the right approach?


Solution

  • I am a little late in the game, but maybe the following snippet is still of interest? It picks up the idea of creating a lookup object itms and for each shopping cart entry it also combines two objects into a new one with a subtotal subt, so you can easliy create a meaningfull shopping cart table. The variable ttl is updated alongside and contains the total sum:

    const items = [
     {
      "id": "001",
      "name": "apple",
      "price": 500
    },
    {
      "id": "002",
      "name": "banana",
      "price": 700
    },
    {
      "id": "003",
      "name": "pear",
      "price": 200
     }
    ],
      cart = [{
      "id": "001",
      "qty": 2
    },
    {
      "id": "002",
      "qty": 3
    },
    {
      "id": "003",
      "qty": 4
    }
    ];
    // Turn the items array into an object, facilitating a fast lookup:
    const itms=items.reduce((a,c)=>(a[c.id]=c,a),{});
    let ttl=0;
    // calculate the totals:
    const res=cart.map(c=>{
      const p=itms[c.id], subt=c.qty*p.price;
      ttl+=subt;
      return {...c,...p,subt}
    })
    
    // Show the result:
    console.log(res,ttl);