-2

[Object, Object, Object, Object]

Object{
       id:33,
       val:'a'
      },
Object{
       id:56,
       val:'b'
      },
Object{
       id:77,
       val:'a'
      },
Object{
       id:89,
       val:'d'
      }

Now I want to delete the Object where id = 56

How can I do that using js?

There is the result I want.

[Object, Object, Object]

Object{
       id:33,
       val:'a'
      },
Object{
       id:77,
       val:'a'
      },
Object{
       id:89,
       val:'d'
      }

Thanks.

JSN
  • 5
  • 1
  • 1
    search for that element and delete it? – King King Oct 20 '14 at 05:29
  • possible duplicate of [JavaScript Array Delete Elements](http://stackoverflow.com/questions/500606/javascript-array-delete-elements) – Adam Oct 20 '14 at 05:30
  • for that first you need to search object with id=56 from array then use splice() to delete object form array – Sohil Desai Oct 20 '14 at 05:31
  • you find the answer in this post [enter link description here][1] [1]: http://stackoverflow.com/questions/9187337/jquery-javascript-remove-object-data-from-json-object – mehdiraddadi Oct 20 '14 at 05:36

1 Answers1

0

How about using delete? Please note the index order won't be preserved with this.

var text = '{"objects" : [{ "id":33, "val":"a"}, { "id":56, "val":"b"}, { "id":77, "val":"c"}, { "id":89, "val":"d"}]}';
var jsonData = JSON.parse(text);
for (var i = 0; i < jsonData.objects.length; i++) {
    var object = jsonData.objects[i];
    if(object.id == 56) {
        delete jsonData.objects[i];
    }
}

If you want to preseve the index order then use below code.

var text = '{"objects" : [{ "id":33, "val":"a"}, { "id":56, "val":"b"}, { "id":77, "val":"c"}, { "id":89, "val":"d"}]}';
var jsonData = JSON.parse(text);
for (var i = 0; i < jsonData.objects.length; i++) {
    var object = jsonData.objects[i];
    if(object.id == 56) {
        jsonData.objects.splice(i, 1);
    }
}
user1401472
  • 2,203
  • 3
  • 23
  • 37