Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splicing first object returns TypeError: Cannot read property of undefined

I have an array like this:

var arrSession = [ { name: 'Product 01', groupID: '50303', delivery: 'mail'}, { name: 'Product 02', groupID: '50403', delivery: 'bike'} ]

And this Loop to delete specific objects:

for(var i=0, len=arrSession.length; i<len; i++) {
    if (arrSession[i].groupID == getGroupID && arrSession[i].delivery == getDelivery) {
        arrSession.splice(i, 1);
    }
}

If I'm deleting the last object, all works fine:

var getGroupID = 50403;
var getDelivery = bike;

But if I'm deleting the first object:

var getGroupID = 50303;
var getDelivery = mail;

I get an error:

TypeError: Cannot read property 'groupID' of undefined  

Why so and how to solve it?

Edit:

If there is only one object all is fine too.

var arrSession = [ { name: 'Product 01', groupID: '50303', delivery: 'mail'} ]
like image 229
Philipp M Avatar asked Jan 18 '26 08:01

Philipp M


1 Answers

Short Answer: Due to the for loop syntax. Initialization happens only once. You missed to update len after splicing.

for ([initialExpression]; [condition]; [incrementExpression]) statement

Solution: As already mentioned in the other answers, you can break the loop (which will work if you are spicing only one item).

const arrSessionActual = [{
  name: 'Product 01',
  groupID: '50303',
  delivery: 'mail'
}, {
  name: 'Product 02',
  groupID: '50403',
  delivery: 'bike'
}];

function removeItem(arrSession, getGroupID, getDelivery) {
  for (var i = 0,
      len = arrSession.length; i < len; i++) {
    if (arrSession[i].groupID == getGroupID && arrSession[i].delivery == getDelivery) {
      arrSession.splice(i, 1);
      len = arrSession.length; // This is missing
    }
  }

  console.log(arrSession);
}

removeItem(arrSessionActual.slice(), 50403, 'bike');
removeItem(arrSessionActual.slice(), 50303, 'mail');
like image 141
Sree.Bh Avatar answered Jan 20 '26 03:01

Sree.Bh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!