0

Hi I'm trying to change the ajax get key depend of the king of JSON file.

Here is my quick code :

$("#cbox2").click(function() {
  var jsonlink = $('#jsonlink').val();
  var jsonkey = $('#jsonkey').val();
  $.ajax({
    type: "GET",
    url: jsonlink,
    dataType: 'json',
    cache: false,
    success: function(data) {
      data.forEach(function(post) {
        $('#listacroche').append('<div class="row"><div class="col s5"><input name="foo" value="' + post.email + '" type="checkbox"   id="checkgrp' + post.email + '" /><label for="checkgrp' + post.email + '">' + post.email + '</label></div></div>');
      });
    },
    complete: function() {
      console.log("List des groupes avec succès");
    }
  });
});

As you can see on the code the key is 'post.email' but if on another file it's 'post.userlog' or event 'post.mail' I would like to put the key in my #jsonkey input rather than changing my code.

Thanks

Thomas Darvik
  • 748
  • 7
  • 22
  • Possible duplicate of [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Andreas May 06 '18 at 15:14

2 Answers2

0

You could also access the property with Bracket Notation like post['email']

So use your jsonkey variable can be used like post[jsonkey]

Hope this helps.

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
0

So here is the code working and completed.

$("#cbox2").click(function(){
var jsonlink      = $('#jsonlink').val();
var jsonkey       = $('#jsonkey').val(); //The input KEY
$.ajax({
type: "GET",
url: jsonlink,
dataType: 'json',
cache: false,
success: function(data) {
data.forEach(function(post) {
var jsondakey     = post[jsonkey]; //Where the key is used to get the correct data
$('#listacroche').append(  '<div class="row"><div class="col s5"><input name="foo" value="' + jsondakey + '" type="checkbox" id="checkgrp' + jsondakey + '" /><label for="checkgrp' + jsondakey + '">' + jsondakey + '</label></div></div>'  );
});
},
complete: function() {
console.log("List des groupes avec succès");
}
});
});