Remove element from multidimensional array

后端 未结 6 1713
情歌与酒
情歌与酒 2021-01-13 06:10

I have following multidimensional array:

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

In this example i want t

相关标签:
6条回答
  • 2021-01-13 06:43
     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.

    0 讨论(0)
  • 2021-01-13 06:48
    var arr=[[10,20,30],[40,50,60],[70,80,90]];
    
    for(var i=0;i<arr.length;i++){
        for(var j=0;j<arr[i].length;j++){
            if(arr[i][j]==50){
                arr[i].splice(j,1);
            }
        }
    }
    
    document.write(arr);
    
    0 讨论(0)
  • 2021-01-13 06:56

    Assign your Object (not an Array) to a variable, this way:

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

    Then do:

    delete o['1'];
    

    That's it!

    0 讨论(0)
  • 2021-01-13 06:58

    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.

    0 讨论(0)
  • 2021-01-13 06:59

    You could use delete in javascript Ex:

    var x = {"2":{"cid":"2","uid":"2"},"1":{"cid":"1","uid":"3"}};
    
    delete x['1'];
    

    Also, check this:

    Deleting Objects in JavaScript

    0 讨论(0)
  • 2021-01-13 07:01

    JavaScript doesn't have multi dimensional Arrays, only arrays and objects. That said: delete theObject['1']; should work just fine

    0 讨论(0)
提交回复
热议问题