-3

I have tried to search the solution alot but no one really helped me.

I have a javascript object:

trucks_obj
= Object {95: _.Kd, 96: _.Kd}

95: _.Kd
96: _.Kd
__proto__: Object

If the if condition is true, I just want to remove element from trucks_obj with specific ID. e.g. I need to remove element with 95 index. I have already tried splice() as well as slice() but nothing worked.

Deletion Code:

$.each(trucks_obj,function(i,e){
            if(($.inArray(i, trucks_arr)) === -1){
                trucks_obj.splice(i,1);
            }
        });
Farjad Hasan
  • 3,354
  • 6
  • 23
  • 38

1 Answers1

5

Just use delete:

delete trucks_obj['95']
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I tried but it didn't worked. is it possible to delete an element of object on which we running, $.each()? – Farjad Hasan Dec 10 '15 at 12:11
  • `var keys = Object.keys(trucks_obj);` will return you array of keys . keys[i] will give you the current key. then you can use `delete trucks_obj[keys[i]];` – Shubham Dec 10 '15 at 12:14
  • it's not a good idea to delete the reference you are actually iterate on. so no. a workaround may be another array with the properties to delete and iterate over the array and delete the properties of the object. – Nina Scholz Dec 10 '15 at 12:14
  • @Shubham, that works. – Nina Scholz Dec 10 '15 at 12:15
  • `delete` is a native Javascript function. A jquery object is not 100% compatible to a plain Javascript object – Reporter Dec 10 '15 at 12:15
  • @NinaScholz The author asked for a way with Jquery – Reporter Dec 10 '15 at 12:16
  • @reporter, "A jquery object is not 100% compatible to a plain Javascript object" do you know other objects in javascript who are not javascript objects? – Nina Scholz Dec 10 '15 at 12:23
  • @NinaScholz you cannot not apply all nativ js methods to a jquery object. The browser will show an 'element is undefined error' message. – Reporter Dec 10 '15 at 12:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/97567/discussion-between-nina-scholz-and-reporter). – Nina Scholz Dec 10 '15 at 22:28