Originally my question was How to Remove Object from jQuery array. < Found the answer, the one from @nnnnnn. Using $.grep
My new question now is how would you save the object that you just removed?
Reason is I wish to be able to push that saved Object back into the Array if the user decides to keep it.
My networks array:
console:
networks array = [object Object],[object Object]
networks: Array[2]
0: Object
count: 1
id: "6"
label: "CompanyName"
type: "Organization"
1: Object
count: 1
id: "12622"
label: "MyGroup"
type: "Group"
From the other answer I'm using this to look in the networks array, find the Object with the type of "Organization" and remove it.
networks = $.grep(networks, function(o,i) { return o.type === "Organization"; }, true);
Is there a simple way to save that entire Object? So it can be pushed back in?
Thanks for taking a look!
1 Answer 1
You could assign the object inside the callback to a variable. This isn't a very clean solution, since such callbacks shouldn't have side effects IMO, but it works without making bigger changes to your code:
var obj;
networks = $.grep(networks, function(o,i) {
if (o.type === "Organization") {
obj = o;
return true;
}
return false;
}, true);
or a bit shorter (and more confusing for people who don't know about the comma operator):
var obj;
networks = $.grep(networks, function(o,i) {
return o.type === "Organization" ? ((obj = o), true) : false;
}, true);
$.grepdid not remove the object form the function :( may be back at square 1$.grepis doing. Note that you are usingo.namein the callback, but your example data doesn't have anameproperty. edit: Yep ;)idornamewhatever, and you can use a simplefor looporlodashto find it in the main array and then remove it there. Usesplice.Namealways justname. Check out this Stackoverflow btw stackoverflow.com/questions/9882284/…