How to remove a specific Object from an array of Objects, by object's property?
给定数组[guid,其他属性,…],
如何从javascript数组中通过其guid(或任何对象属性)删除特定对象?
我想用
1 2 3 4 | var index = game.data.collectedItems.indexOf(entityObj.GUID); if (index > -1) { game.data.collectedItems.splice(index, 1); } |
这不起作用,因为我无法直接标识数组中的值,例如:
1 2 | var array = [2, 5, 9]; var index = array.indexOf(5); |
如图所示:如何在javascript中从数组中删除特定元素?
我建议使用
1 2 3 | game.data.collectedItems = game.data.collectedItems.filter(function(currentObj){ return currentObj.GUID !== entityObj["GUID"]; }); |
这将遍历
注意:由于
这应该适用于所有浏览器:
1 2 3 4 5 6 7 8 9 10 11 12 | 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'); |