Reputation: 23574
I'm looping through an object in javascript and deleting an item that is undefined, using:
for (var key in result) {
if (result.hasOwnProperty(key)) {
var obj = result[key];
if (typeof obj.name === 'undefined') {
delete result[key];
}
}
}
If I don't use the delete
, this iterates just fine. However, when I use delete, I then get the error, 'TypeError: Cannot read property 'name' of undefined'
Any idea what I'm doing wrong here?
Thank you
EDIT: The object being iterated:
{
date: Mon, 02 Apr 2012 17: 48: 17 GMT,
t_date: Mon, 02 Apr 2012 17: 48: 17 GMT,
start: 0,
_id: 4f79e661d7cb8ccc1f000005
} {
date: Mon,n02 Apr 2012 17: 48: 26 GMT,
t_date: Mon, 02 Apr 2012 17: 48: 26 GMT,
start: 0,
_id: 4f79e66ad7cb8ccc1f000006
} {
name: 'testname',
date: Mon, 02 Apr 2012 17: 48: 29 GMT,
t_date: Mon, 02 Apr 2012 17: 48: 29 GMT,
start: 0,
_id: 4f79e66dd7cb8ccc1f000007
}
Upvotes: 1
Views: 264
Reputation: 17822
I'm not 100% sure why you're using the typeof
operator there, but I think you can simplify the if statement to simply:
if(obj === undefined)
I also think the hasOwnProperty
check is redundant, not sure what you are checking for there.
I've created an example to demonstrate this here: http://jsfiddle.net/andrewferrier/RxTF8/ (just use your browser console to see the resultant object).
Upvotes: -1
Reputation: 13139
It means that obj
is undefined
and therefore obj.name causes this error.
It should be:
var obj = result[key];
if (obj && typeof obj.name === 'undefined') {
delete result[key];
}
Upvotes: 6