如果一个属性具有特定值,则删除整个对象

时间:2013-01-12 19:16:01

标签: javascript arrays object

我有一个看起来像这样但有点大的对象数组:

var total =   [{ cost="6.00",  descrip="tuna"},{ cost="5.50",  descrip="cod"}];

我需要一种从数组中删除特定完整对象的方法。是否可以根据属性的值来识别对象的索引?如果是这样,拼接方法看起来可以起作用。

total.splice(x,1);

否则也许我可以在某种程度上使用下面的内容?可以为数组中的对象指定名称并以某种方式使用它:

delete total[];

5 个答案:

答案 0 :(得分:4)

不确定你的问题是什么。首先,您必须找到要删除的项目:

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);

我假设数组中至少有一个对象符合条件。

答案 1 :(得分:2)

对于符合ES5标准的浏览器,您可以使用filter()。例如。删除所有费用&lt; 6:

total = total.filter(function(item) {
  return item.cost < 6.0; 
});

编辑:或者更简洁的ES6环境版本:

total = total.filter(item => item.cost < 6.0);

答案 2 :(得分:1)

此函数使用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;
}

答案 3 :(得分:0)

我可能误解了,但这不是很简单,你为什么要拼接?

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]
  }
}

答案 4 :(得分:0)

除非使用冒号而不是等于 -

,否则不会初始化您的对象

您可以过滤数组,返回的数组不包含任何值,而是包含那些通过某些测试的值。

这将返回一个花费一美元或更多的项目数组:

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'
    }
]
相关问题