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>
-
Same as here - stackoverflow.com/questions/500606/…Alex P– Alex P2014年12月24日 05:33:39 +00:00Commented Dec 24, 2014 at 5:33
3 Answers 3
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
6 Comments
obj1.messages.splice(2, 1); first argument is start index, second is how many elements to removeobj1 = $.extend({},obj);Use splice:
obj1.messages.splice(2, 1); // at index 2, delete 1 element, inserting nothing
3 Comments
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.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);
});