如何从数组中删除对象?

时间:2015-06-01 14:44:36

标签: javascript jquery html5 append

我试图从阵列中删除对象,我已经尝试过,似乎并没有做得恰到好处。那么有人能够查看我使用的代码

代码:

文件内的数组 - >

[{
  "favouriteLinkContent": "Group",
  "favouriteLinkID": "groupBTNFav"
}, {
  "favouriteLinkContent": "Server",
  "favouriteLinkID": "serverBTNFav"
}, {
  "favouriteLinkContent": "User",
  "favouriteLinkID": "userBTNFav"
}, {
  "favouriteLinkContent": "Sync",
  "favouriteLinkID": "syncBTNFav"
}]



$(document).on('click', '.removeFavourite', function ()
               {

  var buttonValue = $(this).closest('a')[0].innerText;

  // Reading
  $.ajax(
    {
      global: false,
      type: "POST",
      cache: false,
      dataType: "json",
      data: (
        {
          action: 'read'
        }),
      url: 'php/saveFavouriteLinks.php',
      success: function (data)
      {

        $.each(data, function (key, value)
        {
          newValue = ' ' + value['favouriteLinkContent'];

          if (newValue == buttonValue)
          {
            console.log(value['favouriteLinkContent']);
            delete value['favouriteLinkContent']; 
          }
          //$("#favouritesList").append("<li><a id=" + value['favouriteLinkID'] + "><i class='fa fa-dashboard fa-fw'></i> " + value['favouriteLinkContent'] + "<i class='glyphicon glyphicon-minus pull-right removeFavourite'></i></a></li>");
        }); 
      }
    });

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

我想要发生的事例

按钮点击 - &gt;按钮值为Group - &gt;从数组中删除组 - &gt;

{"favouriteLinkContent":"Group","favouriteLinkID":"groupBTNFav"}

- &GT;删除后 - >

[{
  "favouriteLinkContent": "Server",
  "favouriteLinkID": "serverBTNFav"
}, {
  "favouriteLinkContent": "User",
  "favouriteLinkID": "userBTNFav"
}, {
  "favouriteLinkContent": "Sync",
  "favouriteLinkID": "syncBTNFav"
}]

3 个答案:

答案 0 :(得分:2)

您可以使用带有Array过滤器的辅助函数:

var removeObjectFromArray = function(array, property, objName){          
    return array.filter(function(e){
        return e[property] != objName;
    });
}


 console.log(removeObjectFromArray(array, 'favouriteLinkContent', 'Group'));

JSFiddle

答案 1 :(得分:1)

您可以使用splice

for(var i=0;i<arr.length;i++){
  if(arr[i].favouriteLinkContent === "Group"){ // <---- if you want to remove Group
    array.splice(i, 1); 
    i--;  // <--- have to do i-- because splice changes the array and array size will be altered
  }
}

您可以将其包装在函数中,并根据项

从数组中删除元素
removeElement(arr, "Group");

function removeElement(arr, item) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].favouriteLinkContent === item) { 
      array.splice(i, 1);
      i--;
    }
  }
}

答案 2 :(得分:1)

您可以使用过滤功能 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Array/filter

function removeGroup (arr, groupName) {
    return arr.filter(function (el) {return el.favouriteLinkContent !== groupName;});
}

希望它有所帮助, 丹