How to change an item in a json

Asked

Viewed 6,238 times

3

I have a JSON array like this:

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

I would like to know how to add/change an item into a id only. As if in SQL.

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

  • 1

    The title of the question says "add", but by its description you want to "select". It is a bit ambiguous, could you explain better what you want? (would be maybe add if not there, change if you are?)

  • 1

    I’m sorry I would change the value of an item.

3 answers

3


If you only want to change the value of the object whose ID is 2, you will have to go through all elements/objects of that array. If you do it with a loop for you can use the 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: http://jsfiddle.net/u97dr92y/1/

3

I don’t know Angularjs, but I believe filter can do what you want (just not understood by the documentation how to use it). To do in pure Javascript, 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);

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

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 by id you can use an object instead of the array in 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 in a similar way to a HashMap(Java) or Dictionary(C#), then json.Prop is the same as json["Prop"].

  • And change the total id: 1, for example ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.