I want to remove the 'hello5' from the years in myObj.
I used 'pop' prototype, but the browser console return this result :
'Uncaught TypeError: Cannot read property 'type' of undefined'
The following is an example for my issue. You could try and will see error message from console.
I tried a long time but I didn't find any solution, I need your advise and solution.
Code :
var myObj = {
test : 'testObje',
langs : {
0 : 'EN',
1 : 'GR',
2 : 'RU',
3 : 'TR'
},
comment : 'testComment'
};
var years = [];
for (i= 0; i<=10; i++)
{
years.push({
operator : i,
type : 'hello' + i
});
};
myObj.years = years;
var myObjLeng = myObj.years.length;
for(var i = 0; i < myObjLeng; i++) {
if(myObj.years[i].type == 'hello5') {
myObj.years.pop();
}
}
What about this one?
in short you take
myObj.years
array an filter each of its elements calledyear
in filiter callback. Filter will pass-thru these elements whose condition is met. All will met except ones withtype
with your"hello5"
expression. Finally you substitute result back and you are done.Your object key selection was wrong. Instead of for loop I suggest you to use
map()
function.pop will remove the last element, which will change the original array, that's why you are getting "Uncaught TypeError: Cannot read property 'type' of undefined" because after pop the index you are trying to access is not found on the array, instead use "array.filter"
There are some good alternatives here, so let me just take a stab at why you're getting that error.
You're getting that error because you're changing the length of the array mid-loop. At the beginning of the loop, you have 11 elements, and you use that to define how many times your
for
loop will go. When you get tohello5
, youpop
the last element off, making your array 10 elements long. However, yourfor
loop will still try to access the 11th element. That will beundefined
, and when you try to access a proprty ofundefined
(e.g.type
), you will get a TypeError.pop
always removes the last element,pop
mutates original array, which affects index and you end up accessing indexs out of array length, you can simply use filter