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?

11
  • 7
    The first string is not valid JSON, or even JavaScript for that matter. Commented Jan 18, 2013 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. Commented Jan 18, 2013 at 14:08
  • It's all valid i was merely showing the structure in the simplest of terms.... Commented Jan 18, 2013 at 14:09
  • What i put above is just a representation of the json object structure.. Commented Jan 18, 2013 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. Commented Jan 18, 2013 at 14:19

10 Answers 10

21

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 }]
Sign up to request clarification or add additional context in comments.

1 Comment

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];
    }
}

2 Comments

This should be filtered by hasOwnProperty. Also, a key would be unique so there could only ever be one occurrence (=> why loop?).
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.
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;
    }
}

Comments

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)

Comments

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();

Comments

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.

Comments

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/

Comments

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]);
}

4 Comments

is there not a way to do it without looping? would rather avoid that.
Why? You have to loop at some point (or recurse).
well since its essentially an object there is usually a functionality like delete key or something... looping isn't a very elegant solution for removing one portion of an object.
So you want to delete the property and not the object? If so look at Magus's answer.
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}

Comments

-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;

4 Comments

JSON's not even a string, it's a notation like XML
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.
You get a string after JSON.stringify() but not sure what do you mean by all this.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.