UI_Dev
UI_Dev

Reputation: 3427

Removing json Array from json object

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>

Upvotes: 0

Views: 1167

Answers (3)

Suchit kumar
Suchit kumar

Reputation: 11859

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);
        });

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

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

Upvotes: 1

Amadan
Amadan

Reputation: 198314

Use splice:

obj1.messages.splice(2, 1); // at index 2, delete 1 element, inserting nothing

Upvotes: 1

Related Questions