Is it possible to take a data from a JSON using a predefined variable?

Asked

Viewed 50 times

1

I have a link with an attribute that has the information of which JSON data should be obtained.

<a href="#" data-json-code="code_118"></a>

And I have the code responsible for its behavior, which should be:

  1. Take the attribute;
  2. Find this attribute in json;
  3. View json information in the console.

I did this way, but always returns "Undefined":

$('.c-productCard a').on('click', function(event) {
    event.preventDefault();
    var jsonCodeProduct = $(this).attr('data-json-code');

    var jsonUrl = 'https://api.myjson.com/bins/mc9ig';
    $.ajax({
        type: 'GET',
        datatype: 'json',
        url: jsonUrl,
        cache: false,
        beforeSend: function() {
            console.log('before send');
        },
        success: function(result) {
            console.log(result.jsonCodeProduct);
        },
        error: function(xmlHttpRequest, textStatus, errorThrown) {
            console.log('erro');
        },
        complete: function() {
            console.log('complete');
        }
    });
});

If I happen to remove the jsonCodeProduct of the call success the entire json is displayed in the console (as expected).

The question is, how to make the variable die jsonCodeProduct be the "selector" to display the corresponding data from JSON?

  • Have you solved? present the structure of your Json, so I can better elaborate my answer.

  • I got @Leandroangelo, thank you very much, the solution was just what you indicated, just put the "jsonCodeProduct" in brackets after the result.

  • So please mark the proposal as the answer to your question, it will help other people who are going through the same problem to find the fastest solution.

1 answer

2


Just like any object in javascript, you can get the value of a property through its name, in your case it would be:

    success: function(result) {
        console.log(result[jsonCodeProduct]);
    }

See the example below, also if you are using attributes data and jquery you can retrieve the information in a slightly more elegant way.

$('a').on('click', function(event) {
  event.preventDefault();
  var jsonCodeProduct = $(this).data('json-code');

  console.clear();
  console.log(objExemplo[jsonCodeProduct]);


});

var objExemplo = {
  code_118: { nome : 'Produto 1' , preco : 'R$10,00'},
  code_119: { nome : 'Produto 2' , preco : 'R$20,00'}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="exemplo" href="#" data-json-code="code_118">Produto 1</a>
<a id="exemplo" href="#" data-json-code="code_119">Produto 2</a>

Browser other questions tagged

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