0

I have a javascript object which looks like this :-

var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"}, 

                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},

                {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

Now , I have to delete all the rows in the object with id value 2. How can this be done ?

Prashant Singh
  • 3,725
  • 12
  • 62
  • 106
  • you can recreate the array without the deleted part – Ibu Dec 12 '12 at 06:52
  • Does it have to be a mutate operation? – Ray Toal Dec 12 '12 at 06:52
  • What do you have handy? prototype.js? jquery? – Faiz Dec 12 '12 at 06:53
  • I was using plain javascript. Recreating will be a bit slow if the number of rows are very large, I guess. Yes, it will be mutually used – Prashant Singh Dec 12 '12 at 06:56
  • Do you need the original array after you remove the items with the `id` of "2"? – Ian Dec 12 '12 at 07:02
  • @PrashantSingh Understand that mutating by removing rows from an array can be quite inefficient since in general you have to "shift" large chunks of the array. If you can accept creating a new array, see the answer by elclanrs. – Ray Toal Dec 12 '12 at 07:08

5 Answers5

5

If you don't need the original array after "deleting" rows, you can use splice like this:

http://jsfiddle.net/rmcu5/1/

var myArray = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
                {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

function removeItemsById(arr, id) {
    var i = arr.length;
    if (i) {   // (not 0)
        while (--i) {
            var cur = arr[i];
            if (cur.id == id) {
                arr.splice(i, 1);
            }
        }
    }
}

removeItemsById(myArray, "2");

console.log(JSON.stringify(myArray));

It doesn't create a new array, just modifies the original in place. If you need the original array and all of its items, then use one of the other solutions that return you a modified copy of the original.

Ian
  • 50,146
  • 13
  • 101
  • 111
  • +1 for splice as this is the "native" way to remove items from an array. – Ray Toal Dec 12 '12 at 07:10
  • Can you explain a bit about arr.splice ? – Prashant Singh Dec 12 '12 at 10:12
  • 2
    @PrashantSingh It takes 3 parameters (only the first 2 we're worried about). The first parameter is the index to start removing items from, and the second parameter is how many items to remove. I just set it as `1` because we only want to remove the single item in the loop (its `id` is `2`) – Ian Dec 12 '12 at 10:24
  • 1
    @PrashantSingh The looping starts at the end of the array and loops to the beginning, which is important for something like this because you're modifying the array directly while looping through it and can throw off the looping – Ian Dec 12 '12 at 10:25
  • 1
    @PrashantSingh No problem. Just remember, this modifies the original array. If you want to keep the original array in its state but also get a copy that has specific items removed, you would need to use someone else's solution. It really depends on what you specifically need to do – Ian Dec 12 '12 at 15:49
  • I am not interested in the original array. – Prashant Singh Dec 12 '12 at 21:06
4

Note that what you call myObject is actually an array therefore you can use array methods on it:

myObject = myObject.filter(function( obj ) {
  return obj.id != 2;
});

Demo: http://jsfiddle.net/elclanrs/LXpYj/

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • 3
    That's very nice but the OP did ask for a mutator. I don't agree with the OP's request for a mutator. Your solution is obviously the best, since removing from the middle of an array is awful. If the OP agrees that this is okay, I'll +1. – Ray Toal Dec 12 '12 at 07:06
  • @PrashantSingh Note that this is not available on IE < 9. You'd have to include a polyfill just for the `filter` method to work on them – Ian Dec 12 '12 at 10:02
  • @Ian Ok, that means I can't use this :O – Prashant Singh Dec 12 '12 at 10:12
  • Yes but you need to add a _polyfill_ for older browsers. A polyfill is just some code that adds that functionality if is not present. There's a 140bytes `filter` polyfill here: https://gist.github.com/1031656. Even with the polyfill the code will be shorter and more readable than most other ways of doing this. – elclanrs Dec 12 '12 at 10:14
2

try this:

function deleteObject(array,id)
{
 var newObject=[]; 
  for (var o in array) {
       if(array[o].id!=id)
          newObject.push(array[o]);
    }
return newObject;
}

working JS fiddle

You can do without creating new array, you need to write remove function:

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

Without New Array Delete Object

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

try it with filter (its an array not a object)

var rr = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},  {"id": "2", "URL": "http://shsusadhf.com", "value": "2"}, {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];


rr = rr.filter(function(e) {
    return e.id != 2;
});
silly
  • 7,789
  • 2
  • 24
  • 37
-1

Here you go, this is without recreating the array or anything.

 var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"}, 

                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},

    {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

for(i=0,iMax=myObject.length;i<iMax;i++){
    (function (a) { 
        if(this.id=="2"){
          delete myObject[a];
        }
    }).call(myObject[i],i);
}

console.log(myObject);
​
​

jsFiddle

http://jsfiddle.net/gG2zz/1/

Muqito
  • 1,369
  • 3
  • 13
  • 27
  • You do realize that [**THIS**](http://jsfiddle.net/gG2zz/2/) would do exactly the same, and it still would'nt remove anyting, it just sets the array items to undefined ? – adeneo Dec 12 '12 at 07:06
  • @adeneo well I'm sorry if it's late and I'm tired. but why do you say it doesn't delete it [link](http://stackoverflow.com/questions/346021/how-do-i-remove-objects-from-a-javascript-associative-array) – Muqito Dec 12 '12 at 07:11
  • 1
    delete works fine on objects, like in the linked question, but on arrays the index is not updated, and the length would still be the same, so it's not really "deleted", that's the main problem with arrays, deleting stuff is a pain in the a$$, and usually takes some slicing and dicing. – adeneo Dec 12 '12 at 07:14