简体   繁体   English

如何通过对象的属性从对象数组中删除特定的对象?

[英]How to remove a specific Object from an array of Objects, by object's property?

Given array [{GUID, other properties}, ...], 给定数组[{GUID,其他属性},...],

How can I remove a specific object from a javascript array by its GUID (or any object property)? 如何通过GUID(或任何对象属性)从javascript数组中删除特定对象?

I'm trying to use splice() , 我正在尝试使用splice()

var index = game.data.collectedItems.indexOf(entityObj.GUID);
if (index > -1) {
    game.data.collectedItems.splice(index, 1);
}

This won't work because I can't directly identify the value in the array, as such: 这不起作用,因为我无法直接识别数组中的值,因此:

var array = [2, 5, 9];
var index = array.indexOf(5);

Shown here: How do I remove a particular element from an array in JavaScript? 如下所示: 如何从JavaScript中删除数组中的特定元素?

I would recommend using the Array.prototype.filter function, like this 我建议使用Array.prototype.filter函数,就像这样

game.data.collectedItems = game.data.collectedItems.filter(function(currentObj){
    return currentObj.GUID !== entityObj["GUID"];
});

This would iterate through the elements of game.data.collectedItems and filter out the items for which the function passed as a parameter, returns false . 这将迭代game.data.collectedItems的元素并过滤掉函数作为参数传递的项,返回false In your case, all the objects will return true except the object whose GUID matches entityObj["GUID"] . 在您的情况下,除GUIDentityObj["GUID"]匹配的对象外,所有对象都将返回true

Note: Since filter creates a new Array, we need to replace the old array object with the new array object. 注意:由于filter创建了一个新的Array,我们需要用新的数组对象替换旧的数组对象。 That is why we are assigning the result of filter back to game.data.collectedItems . 这就是为什么我们将filter的结果分配给game.data.collectedItems

This should work on all Browsers: 这适用于所有浏览器:

function withoutPropVal(ary, propVal){
  var a = [];
  for(var i=0,l=ary.length; i<l; i++){
    var o = ary[i], g = 1;
    for(var n in o){
      if(o[n] === propVal)g = 0;
    }
    if(g)a.push(o);
  }
  return a;
}
var newArray = withoutPropVal(yourArray, 'Object Property Value to Leave those Objects Out Here');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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