我有一个看起来像这样但更大一点的对象数组:
var total = [{ cost="6.00", descrip="tuna"},{ cost="5.50", descrip="cod"}];
我需要一种从数组中删除特定完整对象的方法。是否可以根据属性的值来识别对象的索引?如果是这样,拼接方法看起来可以工作。
total.splice(x,1);
否则,也许我可以以某种方式使用以下内容?可以给数组中的对象命名并以某种方式与它一起使用:
delete total[];
我有一个看起来像这样但更大一点的对象数组:
var total = [{ cost="6.00", descrip="tuna"},{ cost="5.50", descrip="cod"}];
我需要一种从数组中删除特定完整对象的方法。是否可以根据属性的值来识别对象的索引?如果是这样,拼接方法看起来可以工作。
total.splice(x,1);
否则,也许我可以以某种方式使用以下内容?可以给数组中的对象命名并以某种方式与它一起使用:
delete total[];
不太确定你的问题是什么。您首先必须找到要删除的项目:
function findItem(arr) {
for(var i = 0; i < arr.length; ++i) {
var obj = arr[i];
if(obj.cost == '5.50') {
return i;
}
}
return -1;
}
该findItem(total)函数将返回一个元素匹配cost == '5.50'条件的索引(当然你可以使用另一个)。现在你知道该怎么做了:
var i = findItem(total);
total.splice(i, 1);
我假设数组中至少有一个对象与条件匹配。
对于 ES5 兼容的浏览器,您可以使用filter(). 例如,删除所有成本 < 6 的项目:
total = total.filter(function(item) {
return item.cost < 6.0;
});
编辑:或者更简洁的 ES6 环境版本:
total = total.filter(item => item.cost < 6.0);
此函数使用 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;
}
除非您使用冒号而不是等号,否则您的对象不会被初始化 -
您可以过滤一个数组,返回的数组不包含任何值,但那些通过了一些测试。
这将返回花费一美元或更多的项目数组:
var total= [{
cost:"6.00", descrip:"tuna"
},{
cost:"5.50", descrip:"cod"
},{
cost:".50", descrip:"bait"
}
].filter(function(itm){
return Number(itm.cost)>= 1;
});
/* 返回值:
[{
cost:'6.00',
descrip:'tuna'
},{
cost:'5.50',
descrip:'cod'
}
]
我可能理解错了,但这不是很简单,为什么要拼接?
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]
}
}