[英]How to remove object from a array?
I'm trying to remove object from array, I've tried and don't seem to be getting just right. 我正在尝试从数组中删除对象,我已经尝试过并且似乎并不正确。 So would someone be able to look at my code used 所以有人可以看看我使用的代码
Code: 码:
Array inside files -> 数组内部文件->
[{
"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>"); }); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Example of what I want happening 我想要发生的事的例子
Button Click -> Button value is Group -> Remove Group from Array -> 按钮单击->按钮值是组->从阵列中删除组->
{"favouriteLinkContent":"Group","favouriteLinkID":"groupBTNFav"}
-> After deletion -> ->删除后->
[{
"favouriteLinkContent": "Server",
"favouriteLinkID": "serverBTNFav"
}, {
"favouriteLinkContent": "User",
"favouriteLinkID": "userBTNFav"
}, {
"favouriteLinkContent": "Sync",
"favouriteLinkID": "syncBTNFav"
}]
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
}
}
You can wrap it in a function and remove the element from array based on the item 您可以将其包装在函数中,然后根据项目从数组中删除元素
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--;
}
}
}
You can use filter function https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Array/filter 您可以使用过滤器功能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;});
}
Hope it helps, Dan 希望能帮上忙,丹
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.