Update JSON value with JavaScript

2

How can I update the data.dM value without having to rewrite everything reset ..? When I do data.dM = 'lalalaa'; the value is not updated in data

var data = [{
    "dM": 'lolololo'
}];

data.dM = 'lalalaa';
    
asked by anonymous 23.05.2015 / 00:25

2 answers

4

What you have there is an array, with one (and only one) object inside it. So you need to access the first position of the array before you can access the object's dM property:

data[0].dM = 'lalalaa';
    
23.05.2015 / 00:43
2

Quick response:

var data = [{
    "dM": 'lolololo'
}];

    for(var i=0; i < data.length; i++){
        data[i].dM= "dado " + i;
    }
    alert(JSON.stringify(data));

The answer @bfavaretto is correct however to understand it we need to know some concepts, in the example:

var alunosSalaAula = [
    {
        "nome": "jaozinho"
    },
    {
        "nome": "mariazinha"
    }
];

- What do we have?

A JSON

- But what is JSON?

JSON is a standardized string for storing data that when interpreted by javascript becomes arrays and objects.

- So how's your structure?

Basically when we have the following JSON we have an empty array, the brackets indicate an array

[]

When we have something in between keys we have an object, in the example below we have an array with an object inside that has no property

[{}]

JSON can also come with an object that has an array inside, etc.

{pessoas: ["joao", "maria"]}

- Why do I need to know this?

Why knowing that a JSON is nothing more than arrays and objects is easy; returning to the last example if I have an array of student objects how to "walk" through them? that is, how to walk in an array? Using for!

var alunosSalaAula = [
    {
        "nome": "jaozinho"
    },
    {
        "nome": "mariazinha"
    }
];
for(var i=0; i < alunosSalaAula.length; i++){
    alunosSalaAula[i].nome = "aluno " + i;
}
alert(JSON.stringify(alunosSalaAula));

As stated by @bfavaretto JSON is the object in String state, which would be something like

var json = '{pessoas: ["joao", "maria"]}';
// convertendo para ojjeto javascript
var objeto = JSON.parse(json);

If you already have it literally, this is not necessary;

    
23.05.2015 / 01:42