【问题标题】:Removing an object from an array using one value [duplicate]使用一个值从数组中删除对象[重复]
【发布时间】:2016-11-07 09:39:36
【问题描述】:

可能是初学者提出的一个非常明显的问题:

如果我有以下数组...

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 循环似乎非常繁重。

谢谢!

【问题讨论】:

标签: javascript jquery arrays oop


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您可以使用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 是要走的路
    • 效果很好。谢谢!
    【解决方案3】:

    你可以使用JQuery的grep

    arr = jQuery.grep(arr, function(value) {
      return value.id != id;
    });
    

    【讨论】:

    • 这也很有效。谢谢!
    猜你喜欢
    • 2018-11-14
    • 2020-12-31
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    • 1970-01-01
    • 2019-11-23
    • 2012-07-24
    相关资源
    最近更新 更多