How to add and remove items from a json easily?

1

I have a json similar to this

[{id: 1, titulo: 'compra', valor: 50.00, data:'2014-10-23' },{id: 1, titulo: 'compra', valor: 60.00, data:'2014-10-24' } ]

I have a function to add, which adds a new item and one to remove. The add function is ok, but I would like to know how I can remove an item.

There may be several items that are the same but on different dates, that is, multiple items with the same ID only with different dates.

    
asked by anonymous 16.02.2015 / 21:51

3 answers

1

The function below removes the JSON entry by any key.

It will serve you like a glove! ;-) ( demo )

var meuJSON = [{id: 1, titulo: 'compra', valor: 50.00, data:'2014-10-23' },{id: 1, titulo: 'compra', valor: 60.00, data:'2014-10-24' } ];

function removerPela(chave, valor){
    meuJSON = meuJSON.filter(function(jsonObject) {
        return jsonObject[chave] != valor;
    });
    return meuJSON
}

console.log(removerPela("data","2014-10-23"));
    
16.02.2015 / 23:02
1

If you want to remove all the elements of the array with a certain ID you can do this:

function removerID(id, arr) {
    return arr.map(function (obj) {
        if (obj.id != id) return obj;
        else return false;
    }).filter(Boolean);
}

jsFiddle: link

In this case I suggest 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 indexes of objects that have a certain ID but this only makes the code more complex and I doubt it will greatly improve the performance of 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);

jsFiddle: link

    
16.02.2015 / 23:27
0

You can do this using the delete function. Take a look at here . Tip: An id is a unique identifier. Do not use the same id for more than one different element.

    
16.02.2015 / 22:33