Reputation: 1617
I'm having trouble deleting/removing an item from an Array in jQuery. I've run the results in console.log() and it shows up as an Object. I've created a function which returns a json string and then I parses it, an example below:
var ret = jQuery.parseJSON($.return_json(data));
It works nicely, however, I am running an $.each
loop which removes items from that array/object.
var old = $("element").find("li[rel=item]");
$.each(old, function(index, value) {
ret.splice($(value).attr("id"), 1);
});
Above, I am searching for elements with attribute rel = item
. The same element contains an id
which is related to the index of the function which returns the json parsed variable.
I ran Developers Tools in Google Chrome to see the error and it prints:
Uncaught TypeError: Object #<Object> has no method 'splice'
Any words of guidance will be much appreciated. Thanks.
Upvotes: 2
Views: 11029
Reputation: 227240
splice
is only a method of arrays, not objects. ret
in this case, is an object, not an array.
If you are trying to remove specific elements from an object, you can do this:
$("element").find("li[rel=item]").each(function(i,v){
delete ret[v.id];
});
ps. You can use .each
instead of $.each
.
If you really want to make the object into an array, you can simply loop through it and push the elements into an array.
var obj = {"1":"item 1", "2": "item 2", "3": "Item 3"};
var arr = [];
for(i in obj){
if(obj.hasOwnProperty(i)){
arr.push(obj[i]);
}
}
Upvotes: 3
Reputation: 4075
It seems like ret
is not actually an array (and likely an object (ex: {someName: "someVal"}
) instead).
I'm also making an assumption that you mean for $(value).attr("id")
to be a string identifier like someName
in the object example above. If that is the case and you are working with an object and you do have the appropriate property identifier, then luckily there is an easier solve than splice
.
Try:
$("element").find("li[rel=item]").each(function() {
delete ret[$(this).attr("id")];
});
Upvotes: 4
Reputation: 13476
ret is the JSON object containing the array, and you can't splice it. You need to reference whatever you called the array within the object and splice that.
(Would help if you posted the code where you define the array).
Upvotes: 0