Update JSON value with Javascript

Asked

Viewed 1,865 times

2

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

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

data.dM = 'lalalaa';

2 answers

3

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

data[0].dM = 'lalalaa';
  • this zero should be used regardless of the position of dm?

  • Zero is the position of the object (which contains the dM) inside the array.

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 @bfavaretto answer is correct but to understand it we need to know some concepts, in the example:

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

- What 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 is its structure?

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

[]

When we have something 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 makes it easy; going back to the past example if I have an array of student objects like "walking" through them? i.e., how to walk in an array? Using!

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 the 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, that doesn’t make it necessary;

  • 1

    Good explanation, but none of this is json (except what you pass to Alert at the end of the examples). They are literal objects and arrays. They only become json when serialized.

  • @bfavaretto, yes but what he has is also not JSON, so I imagine he can convert

Browser other questions tagged

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