Reputation: 3029
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"
}]
Upvotes: 0
Views: 147
Reputation: 3134
You could use a helper function with Array filter:
var removeObjectFromArray = function(array, property, objName){
return array.filter(function(e){
return e[property] != objName;
});
}
console.log(removeObjectFromArray(array, 'favouriteLinkContent', 'Group'));
Upvotes: 2
Reputation: 695
You can use filter function 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
Upvotes: 1
Reputation: 33618
You can use 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
}
}
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--;
}
}
}
Upvotes: 1