Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from multidimensional array

I have following object:

{"2":{"cid":"2","uid":"2"},"1":{"cid":"1","uid":"3"}}

In this example I want to remove

"1":{"cid":"1","uid":"3"}

from it. I have tried all solutions that I found on Stack Overflow, and could not make any of them work. I am mostly PHP person, so I might miss something important here?

like image 932
Milos911 Avatar asked Apr 16 '12 13:04

Milos911


2 Answers

Just use delete with the appropriate property.

var obj = {"2":{"cid":"2","uid":"2"},"1":{"cid":"1","uid":"3"}};

delete obj["1"];

Note the " around the 1 to mark it as an identifier and not as an array index!

EDIT As pointed out in the comment, obj is an object and no array no matter how you address the [1] property. My last note was just to make it clear that you are working with an object and not an array.

In my experience most people associate integer properties with arrays and string properties with objects. So I thought it might be more helpful to highlight the property in the way given.

like image 57
Sirko Avatar answered Oct 25 '22 21:10

Sirko


 var myObj= {"2":{"cid":"2","uid":"2"},"1":{"cid":"1","uid":"3"}}

delete myObj['1'];

alert ( myObj['1']);

please notice there are Cross platform problems with delete :

Cross-browser issues

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

like image 37
Royi Namir Avatar answered Oct 25 '22 20:10

Royi Namir