-4

I am trying to remove an object based on the obj id.

I have something like

var array =[];
var id =3;

array [
   {
    id:'1',
    title:'test'
   },
   {
    id:'2',
    title:'tes2'
   },
   {
    id:'3',
    title:'tes3'
   }
]

How do I remove the object based on the id 3. thanks!

BonJon
  • 779
  • 1
  • 7
  • 21

2 Answers2

3

Use filter():

array = array.filter( 
          function( item ) {
            return item.id != id;
          }
        );

Or, to modify the array in place:

for ( i = 0; i < array.length; ++i )
{
  if (array[i].id == id)
  {
    array.splice(i, 1);
    break;
  }
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

As an alternative to the previously-posted answer, if you, or your users, are using an up-to-date browser, then the following is available:

function removeByPropertyEquals(haystack, needleProp, needleVal) {
    haystack.forEach(function (obj, index) {
        if (obj[needleProp] === needleVal) {
            return index;
        }
    });
    return -1;
}

var id = 3,
    array = [{
        id: '1',
        title: 'test'
    }, {
        id: '2',
        title: 'tes2'
    }, {
        id: '3',
        title: 'tes3'
    }];

console.log( array );

array.splice(removeByPropertyEquals(array, 'id', '3'), 1);

console.log( array );

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410