0

I am trying to itterate trough a jquery array, and I am having an error The script causing the error is:

$.each(amount, function (key, value) {
    console.info('>>> Selected line: '+value.value + " " + value.currency);
    if ((value.currency == currency) && (value.value == val)) {
        amount.splice(key,1);
        console.info('Deleted: [' + value.value + " " + value.currency+ "] from line "+ key);
    }
});

The error firebug throws is:

TypeError: value is undefined

Could someone point me where the error is or how to fix the error?

3
  • amount is an array by the form bellow: Commented May 29, 2014 at 18:06
  • [{value: 100, currency: 'EUR'}, {value: 125, currency: 'USD'}] Commented May 29, 2014 at 18:07
  • Did that also, and changed the function (key, value) to function (key, data) but still get the data is undefined Commented May 29, 2014 at 18:09

1 Answer 1

1

The issue is with your .splice(). When you remove item 0, everything moves up a spot, so you no longer have an item 1.

Generally speaking, you can't remove items from a list you're enumerating (unless taking steps to adjust the current index when adding or removing items, but.. yuck).

I would recommend using a filter function like grep instead:

http://jsfiddle.net/DnN4a/

var newArr = $.grep(amount, function(item, idx) {
   return item.currency == currency || item.value == val; 
}, true);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I thaught that it could be related to changing the array, but had no clue about how to avoid splice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.