6

Possible Duplicate:
Delete from array in javascript

I have the following JSON object:

[id:84,id:92,id:123,id:2353]

How would I go about removing the item which the value is "123" using javascript?

or if I formatted the json as

[84, 92, 123, 2353]

How would it be removed in this case?

Community
  • 1
  • 1
André Figueira
  • 6,048
  • 14
  • 48
  • 62
  • 7
    The first string is not valid JSON, or even JavaScript for that matter. – Pointy Jan 18 '13 at 14:08
  • 1
    This is extremely confusing. Do you have actual *json*, as in, a string containing the serialized representation of a JavaScript array? Or do you just have a JavaScript array? Because that "JSON string" is *not* valid JSON. – user229044 Jan 18 '13 at 14:08
  • It's all valid i was merely showing the structure in the simplest of terms.... – André Figueira Jan 18 '13 at 14:09
  • What i put above is just a representation of the json object structure.. – André Figueira Jan 18 '13 at 14:10
  • @AndréFigueira it would help everyone out if you would post valid JSON the first time. What you think is an accurate representation may not be the case for many others. – Explosion Pills Jan 18 '13 at 14:19
  • Whether it's deleting an object from an array or just an element from an array, it has been asked more than once for sure. – Felix Kling Jan 18 '13 at 14:23
  • @AndréFigueira, the simplest form of this structure is `[{id:1},{id:2}]` That's small,valid and displays node-information, except that JSON is a string. – Norguard Jan 18 '13 at 14:24
  • I'm down-voting this because it isn't made clear what you exactly want to do, if its remove the array item or delete a key from the object in the array (leading to multiple conflicting answers). Also the provided code is incorrect/incomplete. – Lloyd Jan 18 '13 at 14:27
  • It's abundantly clear... there is an associative object and i want to remove one of the items based on it's value it's all there..... – André Figueira Jan 18 '13 at 14:28
  • @AndréFigueira, it's not even associative, as even if you misused array and set the `id` property 1000 times, it would still only have 1 value for `id`: the last one set. If it is an array or collection of objects, then depict that, because that's what JS uses. Also, the solution you chose isn't going to work in old browsers, without a shim for adding new array stuff. Under the hood, `filter` just uses a loop and returns a second array of all of the items that passed the test in the loop. – Norguard Jan 18 '13 at 14:36
  • @AndréFigueira `[id:84,id:92,id:123,id:2353]` is not JSON. It's not an array. It's not an object. It's not JavaScript AT ALL. It is syntactically invalid and it doesn't even make sense. In JavaScript, Arrays don't have keys, Objects use curly braces, not square, and it makes no sense to use the same key for multiple values because only the last value in the set will ever be returned. Do you understand now? Even written as an object: `a={id:1,id:2}; // a.id === 2`. – glomad Jan 18 '13 at 15:16

10 Answers10

22

Assume you have this:

var items  = [{ id: 84 }, { id: 92 }, { id: 123 }, { id: 2353 }];

var filtered = items.filter(function(item) { 
   return item.id !== 123;  
});

//filtered => [{ id: 84 }, { id: 92 }, { id: 2353 }]
nekman
  • 1,919
  • 2
  • 15
  • 26
9

Supposing you actually have an object from a json in the json variable

for (key in json) {
    if (json.hasOwnProperty(key) && json[key] == 123) {
        delete json[key];
    }
}
Magus
  • 14,796
  • 3
  • 36
  • 51
  • This should be filtered by `hasOwnProperty`. Also, a key would be unique so there could only ever be one occurrence (=> why loop?). – Paul S. Jan 18 '13 at 14:25
  • You are right for `hasOwnProperty`, i fix this. And the loop is because we want to delete a key from its value, and not the key. – Magus Jan 18 '13 at 14:29
3

Shorter alternative would be:

var newArr = [{id:84}, {id:92}, {id:123}, {id:2353}].filter(function(a) {
   return a.id != 123;
});

If you have this:

var arr = [{id:84}, {id:92}, {id:123}, {id:2353}]

To remove the item with value 123, you can do:

for(var i = 0; i < arr.length; i++) {
    if(arr[i].id == 123) {
        arr.splice(i, 1);
        break;
    }
}
techfoobar
  • 65,616
  • 14
  • 114
  • 135
1
function removeClass(obj, cls) {
  var classes = obj.className.split(' ');

  for(i=0; i<classes.length; i++) {
    if (classes[i] == cls) {
      classes.splice(i, 1);
      i--; // (*)
    }
  }
  obj.className = classes.join(' ');

}

var obj = { className: 'open menu menu' }

removeClass(obj, 'menu')
alert(obj.className)
moddom
  • 37
  • 1
1

You can use splice function, like this:

var data = [{id:84}, {id:92}, {id:123}, {id:2353}];
            function remove(){
                for(var i = 0, max = data.length; i < max; i++) {
                    var a = data[i];

                    if(a.id === 123) {
                        data.splice(i, 1);
                        break;
                    }
                }
            }
            remove();
Vismari
  • 745
  • 3
  • 12
1

Seems like you want to avoid a loop. Assuming it's available, you can use .filter:

[{id:84},{id:92},{id:123},{id:2353}]
   .filter(function (elem) { return elem.id !== 123; });

This technically does do a loop, but at least you don't have to look at it.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
1

Assuming your "json" is really an array, like [84, 92, 123, 2353]:

var myString = "[84, 92, 123, 2353]";
var myArray = JSON.parse(myString);
var index = myArray.indexOf(123); // whatever value you are looking for
myArray.splice(index, 1);

http://jsfiddle.net/7vkK6/

Bart
  • 6,694
  • 6
  • 43
  • 53
0

Assuming I'm understanding your question and comments correctly you can do something like this:

var old_array = [{id: 84},...];
var new_array = [];

for(var i = 0, len = old_array.length; i++) {
   if (old_array[i].id != 123) new_array.push(old_array[i]);
}
Lloyd
  • 29,197
  • 4
  • 84
  • 98
0

What you have currently is not JSON so I'll give you some different options.

If you have an Array arr = [84,92,123,2353] then

arr = arr.filter(function (x) {return x !== 123;}); // all occurrences
// OR
arr.splice(arr.indexOf(123), 1); // first occurrence only

If you have an Object obj = {"84": a, "92": b, "123": c, "2353": d}, a to d some expressions, then

delete obj['123']; // obj now {"84": a, "92": b, "2353": d}
Paul S.
  • 64,864
  • 9
  • 122
  • 138
-2

1) JSON is a string, not an array or an object.

var json = "[1,2,3]";

2) Valid JSON NEEDS to be valid JS

var myJSObj = { 1,2,3 }, // broken
    myJSArr = [ name : 1, name2 : 2 ]; // broken

3) If you have a JS Array, you can remove an element by using [].splice

var arr = [ 1, 2, 3, 4 ],
    i = 0, l = arr.length,
    test = 4;

for (; i < l; i += 1) {
    if (arr[i] === test) { arr.splice(i, 1); } // remove 1 starting at i
}

4) If you have an object with named keys, you can use delete

var obj = { val : 1 };
delete obj.val;
Norguard
  • 26,167
  • 5
  • 41
  • 49
  • JSON's not even a string, it's a notation like XML – Explosion Pills Jan 18 '13 at 14:23
  • Yes, okay, but in JS, as a language, there are two ways of dealing with it: as a serialized text-string representation of the markup-lite markup, and with a JSON MIME-type in supporting browsers. – Norguard Jan 18 '13 at 14:29
  • You get a string after JSON.stringify() but not sure what do you mean by all this. – Nizar B. Apr 06 '17 at 19:57
  • @Katcha the question contains hand-written, invalid JSON; not JSON which is generated by serializing JS objects. That's what I meant by all of it. – Norguard Apr 08 '17 at 17:06