Link: Deleting object properties in Javascript

Jul 22, 2011   #php  #javascript 

I was looking for the proper way to delete an object property in Javascript and came upon this nice example. I figured it was worth sharing. I’ve also included a similar way of handling it in PHP.

var obj = {asdf:''foo'',bar:''baz''};
obj.asdf = undefined;
for ( var i in obj ) {
 console.log(i,obj[i]);
}
// outputs:
// asdf undefined
// bar baz

var obj = {asdf:''foo'',bar:''baz''};
delete obj.asdf;
for ( var i in obj ) {
 console.log(i,obj[i]);
}
// outputs:
// bar baz

Using an array in PHP (just for reference) the code would look like:

<?php
$obj = array(''asdf'' => ''foo'', ''bar'' => ''baz'');
$obj[''asdf''] = null;
foreach ( $obj as $key => $val ) {
 echo "$key $val"; 
}
// outputs:
// asdf 
// bar baz

$obj = array(''asdf'' => ''foo'', ''bar'' => ''baz'');
unset($obj[''asdf'']);
foreach ( $obj as $key => $val ) {
 echo "$key $val"; 
}
// outputs:
// bar baz