0

Here, I am deleting the particular Array [2] from the json object. But, what I am seeing in console is -- array values are deleted but it remains in the idx when I checked using $.each in jquery after deleted. So, How to delete the entire array object in a correct way?

var obj = {
   equipments:'first',
 messages:['msg1','msg2','msg3'], 
}

console.log(obj);
$.each(obj.messages, function (idx, obj) { 
alert("before deleted index value" +idx);
});

obj1 = obj;

 if(obj1["equipments"] == 'first' ) {
      delete obj1.messages[2];
   }
   
console.log(obj1);
$.each(obj1.messages, function (idx, obj1) { 
alert("after deleted but index remains same" +idx);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
UI_Dev
  • 3,317
  • 16
  • 46
  • 92

3 Answers3

1

Use splice:

obj1.messages.splice(2, 1); // at index 2, delete 1 element, inserting nothing
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Appreciate Your work! But, I don't know exactly which index I need to delete. I am doing like comparing the values, based on the comparison, it will fetch the particular array index. Then, I am deleting the array. Here, you are using index 2 delete 1 element. What delete 1 means? I know index is 2 – UI_Dev Dec 24 '14 at 05:44
  • If you used `splice(2, 3, "f", "g")`, it would delete the elements at indices 2, 3 and 4 (three of them), and insert `"f"` and `"g"` at index 2 and 3 respectively. It would also change all indices of the following elements by -1, since we inserted one element less than we deleted. If you don't know which index you need to delete, how did you manage with `delete obj1.messages[2]` method, which also needs an index? Find the index, save the world. – Amadan Dec 24 '14 at 05:50
  • Thank you for your help! Kudos for You and @ charlietfl .. Based on the time, I am checking his answer. Sorry for that! Thanks Again! – UI_Dev Dec 24 '14 at 05:52
1

for your current approach try using like this:

        $.each(obj1.messages, function (idx, obj1) { 
            if(typeof(obj1) != 'undefined')// log if the type of obj1 is not undefined because after delete the value will become undefined
        console.log("after deleted but index remains same" +idx);
        });

you can use splice in that case it will remove the index it self like this:

 if(obj1["equipments"] == 'first' ) {
             obj1.messages.splice(2, 1);
           }

    $.each(obj1.messages, function (idx, obj1) { 
        console.log("after deleted  index " +idx);
        });
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
1

When you use delete on an array it doesn't remove that index, it sets the elment to undefined but the array length remains the same.

So you would use splice() but you will also need to realize that whatever you do to obj1 will happen to obj also because obj1 is a reference to obj. it is not a copy when you do obj1=obj

charlietfl
  • 170,828
  • 13
  • 121
  • 150