Delete data from json array

后端 未结 3 1682
清歌不尽
清歌不尽 2021-02-15 00:29

I am trying to remove a piece of a data from a json array. For example I have this array

var favorites =    {
        \"userID\": \"12345678\",
        \"favorit         


        
3条回答
  •  名媛妹妹
    2021-02-15 00:50

    To unset any variable use the delete statement:

    delete favorites.favorites[1].items[1]
    

    This is correct way, and it will work, but if your goal is to preserve indexes in order, then your way with the splice method is the way to go:

    favorites.favorites[1].items.splice(1,1);
    

    The above will remove one element (second parameter) starting at 1st index (first parameter).

    So to be clear: to remove the last element use this:

    var arr = favorites.favorites[1].items;
    arr.splice(arr.length - 1, 1);
    

    See your code on JsFiddle.

    You can take additional measures to protect the code in case the array is not set or empty:

    var arr = favorites.favorites[1].items;
    if ( arr && arr.length ) {
        arr.splice(arr.length - 1, 1);
    }
    

提交回复
热议问题