fawzi_masri
fawzi_masri

Reputation: 113

how dynamically Delete or reset an element from a javascript object

I am trying to delete an object from its parent object without success... When i use 'delete' directly it works, but when i am in a loop over multile objects, i can't get it to work? What am i doing wrong in that $.each loop below:

<script>
 rc = { oc: { 'Amt': 30, 'mpA': 3000, 'ipP': 1, 'ppP': 12, 'mpP': 12000 },
        tb: { 'Amt': 2000, 'mpA': 100000, 'ipP': 1, 'ppP': 12, 'mpP': 12000 },
        bl: { 'Amt': 300, 'mpA': 100000, 'ipP': 1, 'ppP': 12, 'mpP': 12000 }    }

var carObj = {}
carObj['name'] = 'carObj';
console.log ( ' when created: carObj: ', carObj);

carObj['rc'] = rc; 
console.log ( 'when rc Loaded: carObj: ', carObj);

delete carObj['rc'];
console.log ( 'when rc deleted: carObj: ', carObj);

// up till here delete works as expected.
   // create two objects
var carObj1 = {}
var carObj2 = {}
   // load objects with the 'rc' object
carObj1['name'] = 'carObj1';
carObj1['rc'] = rc;
console.log ( 'when rc Loaded: carObj1: ', carObj1);

carObj2['name'] = 'carObj2';
carObj2['rc'] = rc;
console.log ( 'when rc Loaded: carObj2: ', carObj2);


// !!! Here is where delete doe not work.  i don;t get any errors, only rc not deleted from c
$.each([carObj1, carObj2], function (index, c){    
  console.log('before deleting rc', c);
 delete c[rc];
 console.log('After deleting rc', c);
});
</script>

Upvotes: 1

Views: 107

Answers (2)

Nemoy
Nemoy

Reputation: 3417

try using delete['rc'] instead of delete[rc]

Upvotes: 0

Henry
Henry

Reputation: 824

You need to pass it the name of the property, not the object.

delete c['rc'];

Upvotes: 1

Related Questions