DVCITIS
DVCITIS

Reputation: 1037

Delete entire object if one property has certain value

I have an Array of objects that looks like this but a little bigger:

var total =   [{ cost="6.00",  descrip="tuna"},{ cost="5.50",  descrip="cod"}];

I need a way of deleting specific full objects from the array. Is it possible to identify the index of an object, based on the value of a property? The splice method looks like it could work if so.

total.splice(x,1);

Otherwise perhaps I could use the below in someway? can the objects in an array be given names and used with this somehow:

delete total[];

Upvotes: 3

Views: 2627

Answers (5)

broofa
broofa

Reputation: 38142

For ES5-compliant browsers, you can use filter(). E.g. to remove all items with cost < 6:

total = total.filter(function(item) {
  return item.cost < 6.0; 
});

Edit: Or even more concise version for ES6 environments:

total = total.filter(item => item.cost < 6.0);

Upvotes: 4

kennebec
kennebec

Reputation: 104820

Your objects won't be initialized unless you use colons instead of equals-

You can filter an array, the returned array does not contain any values but those that passed some test.

This returns an array of items that cost a dollar or more:

var total= [{
    cost:"6.00", descrip:"tuna"
},{
    cost:"5.50", descrip:"cod"
},{
    cost:".50", descrip:"bait"
}
].filter(function(itm){
return Number(itm.cost)>= 1;
});

/* returned value:

[{
        cost:'6.00',
        descrip:'tuna'
    },{
        cost:'5.50',
        descrip:'cod'
    }
]

Upvotes: 0

tucuxi
tucuxi

Reputation: 17955

This function deletes the first object in an array with object.keyName === value

function deleteIfMatches(array, keyName, value) {
    for (i=0; i<array.length; i++) {
        if (array[i][keyName] === value) {
           return array.splice(i, 1);
        }
    }
    // returns un-modified array
    return array;
}

Upvotes: 1

Pete Mitchell
Pete Mitchell

Reputation: 2879

I may have mis-understood, but isn't this quite simple, why do you want to splice?

var i = 0,
  count = total.length;

// delete all objects with descrip of tuna
for(i; i < count; i++) {
  if (total[i].descrip == 'tuna') { 
      delete total[i]
  }
}

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340933

Not really sure what your problem is. You first have to find which item you want to remove:

function findItem(arr) {
  for(var i = 0; i < arr.length; ++i) {
    var obj = arr[i];
    if(obj.cost == '5.50') {
      return i;
    }
  }
  return -1;
}

The findItem(total) function will return an index of an element matching cost == '5.50' condition (of course you can use another one). Now you know what to do:

var i = findItem(total);
total.splice(i, 1);

I'm assuming there is at least one object in the array matching the condition.

Upvotes: 5

Related Questions