If you want to remove all elements from the array with a certain ID you can do so:
function removerID(id, arr) {
return arr.map(function (obj) {
if (obj.id != id) return obj;
else return false;
}).filter(Boolean);
}
In this case I suggested you do not change the initial array. You can always do arr = removerID(1, arr);
, but if you want to change the array even without passing it to the function you can do the assignment inside the function:
function removerID(id) {
arr = arr.map(function (obj) {
if (obj.id != id) return obj;
else return false;
}).filter(Boolean);
}
Another alternative is to make a map with the index of the objects that have a certain ID but that only makes the code more complex and I doubt that much improves the performance... qq would be something like this:
function removerID(id) {
arr.map(function (obj, i) {
if (obj.id == id) return i;
else return 'foo';
}).reverse().map(function (i) { // uso o reverse para ele usar indexes decrescentes
if (typeof i == 'number') arr.splice(i, 1);
})
}
removerID(1);
Looking at this question and the previous one, I realized that you seem to misunderstand what JSON is. It is a format for data exchange, serialized as string. It is not meant to be manipulated without first being deserialized (which all the answers here and in the other question consider is already done). It may seem like a silly distinction, but it’s important to know.
– bfavaretto
I get it. I’m using it to leave various information in memory to manipulate after the end of a process... I believe that what I want to do can be done in another way. But I appreciate the explanation, it was very useful.
– peterq
What you want to do is correct, I just wanted to make it clear that at this point you no longer operate on JSON, but on normal JS objects and arrays.
– bfavaretto
I understand perfectly. Thank you very much!
– peterq
my friend... shows the function to add new obj in json!! please
– Bruno Dias