简体   繁体   中英

Removing element from JS array of objects

So I have something like this defined

var myList = [];  

//I populate it like this
myList.push({ prop1: value1, 
                      prop2: value2,
                      prop3: value3
});

Is it possible to remove items from the list, based on prop1 value w/o searching through the array?

不可以。您必须以某种方式遍历数组,检查其中每个对象的属性,并在您点击它们时执行删除。

Here you go:

myList = myList.filter( function ( obj ) {
    return obj.prop1 !== value;
});

where value is the value that you're testing against.

Live demo: http://jsfiddle.net/LBYfa/

So, if the value of the 'prop1' property is equal to the value that you're testing against, obj.prop1 !== value will evaluate to false and that element will be filtered out.

Does this help:

Array.prototype.remove = function(s) {
  var i = this.indexOf(s);
  if(i != -1) this.splice(i, 1);
}

Is it required that myList have index of integral type? Might you instead use key => value pairs - that is, an associative array with the value of prop1 as the key? How likely is it that prop1 will be unique? If it's unlikely, consider implementing a multimap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM