How to delete a javascript object item by value?

坚强是说给别人听的谎言 提交于 2020-04-29 12:07:18

问题


Take, for instance, the following object:

var fruits = {
    "red" : "apple",
    "blue" : "blueberry",
    "yellow" : "banana"
}

I know I can use delete fruits["red"] to remove it by the key name, but how could I delete the object item by the fruit name?


回答1:


Have you tried something like this?

function deleteByValue(val) {
    for(var f in fruits) {
        if(fruits[f] == val) {
            delete fruits[f];
        }
    }
}

And as per Rocket's comment, you might want to check hasOwnProperty to make sure you aren't deleting members of the object's prototype:

function deleteByValue(val) {
    for(var f in fruits) {
        if(fruits.hasOwnProperty(f) && fruits[f] == val) {
            delete fruits[f];
        }
    }
}



回答2:


var key = null;
for (var k in fruits){
  if (fruits[k] === 'apple'){
    key = k;
    break;
  }
}
if (key != null)
  delete fruits[key];

Iterate over the object finding the corresponding key, then remove it (if found).




回答3:


Don't know if this is efficient in terms of processing but using filter you can get this done in three lines:

var fruits = {
    "red" : "apple",
    "blue" : "blueberry",
    "yellow" : "banana"
}

var appleless_keys = Object.keys(fruits).filter(this_fruit => fruits[this_fruit] !== "apple");
appleless_obj = {};
appleless_keys.forEach(key => appleless_obj[key] = fruits[key]);
console.dir(appleless_obj);

Or as a function:

var fruits = {
    "red" : "apple",
    "blue" : "blueberry",
    "yellow" : "banana"
}

function remove_fruit(fruit_to_remove,fruits){
  var new_keys = Object.keys(fruits).filter(this_fruit => fruits[this_fruit] !== fruit_to_remove);
  new_obj = {};
  new_keys.forEach(key => new_obj[key] = fruits[key]);  
  return new_obj;
}

console.dir(remove_fruit("apple",fruits));



回答4:


what about this one?

function delteByValue(a){
  fruits.foreach( function( k, v ) {
    if (fruits[v] == a){
      delete fruits[k];
    }
  });
}



回答5:


I think its a good idea to create a function and override the Object.prototype:

/**
 *  @autor Javier Cobos
 *  @param value The value to look for
 *  @return true if founded deleted, false if not
 */        
Object.prototype.removeByValue = function(value){
         var i;
         for(i in this){
            if(this.hasOwnProperty(i))
                if(value === this[i]){
                   delete(this[i]);
                   return true;
                }
         }   
         return false;
        }

// Example
     var fruits = {
        "red" : "apple",
        "blue" : "blueberry",
        "yellow" : "banana"
    }

        fruits .removeByValue("apple");

This way we have a new method for every single Object in our script :)




回答6:


I know you have several acceptable answers at this point... I'm going to include a generic function for this...

// NOTE, replace "Object.removePropertyByValue" 
// with say "jQuery.removePropertyByValue" or "_.removePropertyByValue"
// to create a jQuery or Underscore extension.
Object.removePropertyByValue = function(obj, val) {
  //store list of properties to remove
  var propsToRemove = [];

  for (var prop in obj) {
    if (obj.hasOwnProperty(prop) && obj[prop] === val) {
      //save the property name here, deleting while enumerating is a bad idea.
      propsToRemove.push(prop);
    }
  }

  //remove all the items stored.
  while (propsToRemove.length) delete obj[propsToRemove.pop()];
}

From here you should be able to call: Object.removePropertyByValue(fruits, "red");




回答7:


use this function

function delobj(x,n,v){
    n = "elem."+n;
    var u = x.filter(function(elem, index, self){
        if(eval(n) != v){
            return index == self.indexOf(elem);
        }
    })
    return u;
}

use like this

delobj(object "object name",string "name of element",string "value of element")



回答8:


You can use the splice method

fruits.splice($.inArray("red", fruits), 1);

But this uses jQuery of course.

You can also use this extension:

Array.prototype.remove = function () {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) != -1) {
            this.splice(ax, 1);
        }
    }
    return this;
}



回答9:


var fruits = {
    "red" : "apple",
    "blue" : "blueberry",
    "yellow" : "banana"
}
delete fruits.red; // or use => delete fruits['red'];
console.log(fruits);

this deletes fruits.red



来源:https://stackoverflow.com/questions/9910336/how-to-delete-a-javascript-object-item-by-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!