insert value into a Json data request

Asked

Viewed 42 times

1

I need to write a function that accesses a specific field within a Json file. Json fields are listed as id1, id2, id3... and the value to be accessed will be passed by the function itself. My question becomes clearer by watching the following code:

Javascript

function myFunction (x) {
    fetch ('dados.json')
    .then(function(response){
        return response.json();
    })
    .then(function(data){
        console.log("data.id" + x)
    })
}

Json

{
    "id1":{
            "nome": "João",
            "sobrenome": "Medeiros"
          },
    "id2":{
            "nome": "Mário",
            "sobrenome": "Freitas"
          },
    "id3":{
            "nome": "Joana",
            "sobrenome": "Cunha"
          },

In the above code the value returned in the console is a string, as I do to return the field corresponding to the value provided by X.

From now on, thank you.

  • See if that’s it: console.log(data["id"+x])

  • It worked. Thanks!

2 answers

1

id1 is the name of a property of the object expressed in dados.json. So you can access your value via Bracket Notation, or notation in square brackets:

function myFunction (x) {
    fetch ('dados.json')
    .then(function(response){
        var data = response.json();
        var valor = data['id' + x];
        console.log(valor);
    })
}

0

Access as an index:

var x = { 
    "id1": {
            "nome": "João",
            "sobrenome": "Medeiros"
          },
    "id2":{
            "nome": "Mário",
            "sobrenome": "Freitas"
          },
    "id3":{
            "nome": "Joana",
            "sobrenome": "Cunha"
          }
        };

var num=1

console.log(x["id"+num].nome);

Browser other questions tagged

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