Remove element inside JSON array by value using jQuery

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 item i get

  [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 identifier that I want to find

 var uniqueId = 803641223; 

I want to find the correct id in my video array and delete the entire array. So in this case, I want my last video array to contain only 2 objects instead of 3:

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

My problem is how to get into an array to do my splicing. I prefer to do this with jQuery

Any help please?

+6
source share
4 answers

You can use grep :

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

In vanilla JavaScript, you could use a similar filter function, but it is not supported by IE8.

Note that videos is a JavaScript array, it is not a JSON array, even if it was created by parsing a JSON string.

+13
source

A non-jQuery solution that modifies an array:

 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 changes the original array in place, so that the original videos array will have the elements you need, and the one that matches the uniqueId will disappear (forever). So it depends on whether you want to access the original array again or you can modify it.

It simply uniqueId over the elements of the array, compares the item id property with the value of uniqueId and splice if they match. I use break; right after splice , because you seem to mean that uniqueId can / should only appear once in the array, as it is unique.

+4
source

Hello, you can remove an element using the javascript splice function ...

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

This is working 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 this object.

Hope this helps.

0
source

All Articles