How to change an item in a json

3

I have a JSON Array something like this:

[{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }]

I would like to know how to add / change an item to a id only. Like it was in SQL.

For example, in the case I wanted to change the total of id:2 how could I do it?

    
asked by anonymous 16.02.2015 / 18:18

3 answers

3

If you want to change only the value of the object whose ID is 2, you will have to scroll through all the elements / objects in that array. If you cycle for you can use break; and improve performance.

Something like:

var json = [{
    id: 1,
    total: 50.00
}, {
    id: 2,
    total: 70.00
}];
alert(json[1].total); // 70
for (var i = 0; i < json.length; i++) {
    var obj = json[i];
    if (obj.id == 2) {
        obj.total = 100;
        break;
    }
}
alert(json[1].total); // 100

jsFiddle: link

    
16.02.2015 / 18:30
3

I do not know AngularJS, but I think filter can do what you want ( just did not understand by the documentation how to use it). For pure JavaScript, you can use Array.filter :

var array = [{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }];

var el = array.filter(function(el) { return el.id == 2; })[0];
el.total += 10;

document.getElementsByTagName("body")[0].innerHTML += JSON.stringify(array);

find would be an even better option , but is not widely supported by all browsers.

    
16.02.2015 / 18:34
1

You can add an object to the array with the method push

var lista = [{ id: 1, total: 50.00 }, { id: 2, total: 70.00 }];
lista.push({ id: 3, total: 50.00 });

But if you want to access the array quickly through id you can use an object instead of array itself.

var lista = {};
lista["1"] = { id: 1, total: 50.00 };
lista["3"] = { id: 3, total: 50.00 };
lista["5"] = { id: 5, total: 50.00 };

//Editando o valor do registro com id = 3
lista["3"].total = 300.00;

This is possible because a json object can be accessed similarly to a HashMap (Java) or Dictionary (C #), then json.Prop is the same as json["Prop"] .

    
16.02.2015 / 18:21