I have the following context:
https://jsfiddle.net/eqntaqbt/2/
obj.forEach(function(user, index){
var userName = user.name;
console.log(index, userName);
if(index === 5 || index === 2){
obj.splice(index, 1);
}
});
I am using a forEach
loop and splice
to remove the item in position 5
and 2
on the obj
array. But for some reason its not working properly.
What am I doing wrong?
Your code is splicing while looping. Spliced elements are accessed even they are no more existing. That leads to undefined elements.
You may consider Array#filter
var obj = [{ "index": 0, "name": "Odonnell Noble", "gender": "male", "company": "DIGIQUE", "eail": "[email protected]" }, { "index": 1, "name": "Marie Oneal", "gender": "female", "company": "CANOPOLY", "email": "[email protected]" }, { "index": 2, "name": "Adrienne Marsh", "gender": "female", "company": "XOGGLE", "email": "[email protected]" }, { "index": 3, "name": "Goff Mullins", "gender": "male", "company": "ENDIPIN", "email": "[email protected]" }, { "index": 4, "name": "Lucile Finley", "gender": "female", "company": "AQUASSEUR", "email": "[email protected]" }, { "index": 5, "name": "Pitts Mcpherson", "gender": "male", "company": "QUARX", "email": "[email protected]" }];
obj = obj.filter(function (user, index) {
return (user.index !== 5 && user.index !== 2);
});
document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With