Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an element inside a JSON array by value with 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 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?

like image 730
Lelly Avatar asked Mar 12 '13 17:03

Lelly


People also ask

How to remove specific element from array JavaScript?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

How do you remove an element from a JSON file?

To remove JSON element, use the delete keyword in JavaScript.


1 Answers

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.

like image 67
Denys Séguret Avatar answered Nov 05 '22 07:11

Denys Séguret