Delete an element inside a JSON array by value with jQuery

后端 未结 4 546
夕颜
夕颜 2020-12-19 08:25

Part of my json Array

var videos = $j.parseJSON(\'
  [
    { \"privacy\":\"public\",
      \"id\":\"1169341693\" },

    { \"privacy\":\"private\",
      \"i         


        
相关标签:
4条回答
  • 2020-12-19 08:33

    A non-jQuery solution that modifies the array in place:

    var uniqueId = 803641223;
    var videos = [
        { "privacy":"public",
          "id":"1169341693" },
    
        { "privacy":"private",
          "id":"803641223" },
    
        { "privacy":"public",
          "id":"1300612600" }
    ];
    
    function cleaner(arr, id) {
        for (var i = 0; i < videos.length; i++) {
            var cur = videos[i];
            if (cur.id == uniqueId) {
                arr.splice(i, 1);
                break;
            }
        }
    }
    
    cleaner(videos, uniqueId);
    

    http://jsfiddle.net/4JAww/1/

    Note that this modifies the original array in place, such that the original videos array will have the items you want, and the one that matched the uniqueId will be gone (forever). So it depends on whether you want to be able to access the original array ever again, or are okay with modifying it.

    It just loops through the elements of the array, compares the item's id property to the uniqueId value, and splices if they match. I use break; immediately after the splice because you seem to imply that the uniqueId can/should only appear once in the array since it's...unique.

    0 讨论(0)
  • 2020-12-19 08:38

    You can use grep :

    videos = $.grep(videos, function(e) { return e.id!='803641223' });
    

    In vanilla JavaScript you could have used the similar filter function but it's not supported by IE8.

    Please note that videos is a JavaScript array, it's not a JSON array, even if it was made by parsing a JSON string.

    0 讨论(0)
  • 2020-12-19 08:42

    Hello you can remove element with javascript splice function...

    videos.items.splice(1, 3); // Removes three items starting with the 2nd,
    
    0 讨论(0)
  • 2020-12-19 08:49

    It worker for me.

      arrList = $.grep(arrList, function (e) { 
    
            if(e.add_task == addTask && e.worker_id == worker_id) {
                return false;
            } else {
                return true;
            }
        });
    

    It returns an array without that object.

    Hope it helps.

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