Delete an element inside a JSON array by value wit

2020-02-12 06:32发布

问题:

Part of my json Array

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

    { "privacy":"private",
      "id":"803641223" },

    { "privacy":"public",
      "id":"1300612600" }, ......

When I console.log the element I'm getting

   [Object, Object, Object, …]
       0: Object
           privacy: "public"
           id: "1169341693"
       1: Object
           privacy: "private"
           id: "803641223"
       2: Object
           privacy: "public"
           id: "1300612600"

I also have a unique id I want to search for

var uniqueId = 803641223;

I want to find, in my videos array, the right id, and delete that whole array element. So In that case, I want my final videos array to contain only 2 object, instead of 3 :

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

    { "privacy":"public",
      "id":"1300612600" }, ......

My problem is how to get in the array to do my splice. I prefer to do it with jQuery

Any help please?

回答1:

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.



回答2:

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.



回答3:

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

videos.items.splice(1, 3); // Removes three items starting with the 2nd,


回答4:

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.