使用一个值从数组中删除一个对象

3
可能对初学者来说这是一个非常明显的问题: 如果我拥有以下数组...
var arr = 
  [
    {id: 1, item: "something", description: "something something"},
    {id: 2, item: "something else", description: "something different"},
    {id: 3, item: "something more", description: "more than something"}
  ]

...并希望通过调用ID(在这种情况下,通过点击具有相应ID的div)来删除其中的特定对象...

var thisItem = $(this).attr("id");

我能否不使用for循环来匹配arr[i]thisItem?如果可以,怎么做呢?我的数组很大,运行for循环似乎太笨重了。

谢谢!


对于最新的浏览器:arr.splice(arr.findIndex(o => o.id === 2), 1); - Tushar
3个回答

4

您可以使用Array.filter对任何数组进行过滤。该方法将过滤函数作为其参数,并在原始数组的每个元素上运行它。如果此函数的返回值为false,则该元素将被过滤出返回的新数组中。原始数组不受影响。

var arr = 
  [
    {id: 1, item: "something", description: "something something"},
    {id: 2, item: "something else", description: "something different"},
    {id: 3, item: "something more", description: "more than something"}
  ];

function filterArray( id ){
  return arr.filter(function(item){
    return item.id != id;
  });//filter
}//filterArray()

console.log( filterArray(2) );

array.filter 是最好的选择。 - webdeb
非常好用。谢谢! - dedaumiersmith

2
您可以使用JQuery的grep函数。
arr = jQuery.grep(arr, function(value) {
  return value.id != id;
});

这也完美地运行。谢谢! - dedaumiersmith

0

纯JS解决方案:

var arr = [{
  id: 1,
  item: "something",
  description: "something something"
}, {
  id: 2,
  item: "something else",
  description: "something different"
}, {
  id: 3,
  item: "something more",
  description: "more than something"
}];

var filtered = filterArrayByElemId(arr, 2);
console.log(filtered);

function filterArrayByElemId(arr, id) {
  return arr.filter(function(item) {
    return item.id != id;
  });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接