TurboSupra
TurboSupra

Reputation: 119

Using URL parameter within JSON Object Call

So, I want to take a URL parameter and use it as part of my Javascript Object. I am not able to append that variable within the object, i'm assuming I am missing some sort of concatenating. Thanks in advance for the help.

<script>
    var json = {
    'c100': {
    'url': 'https://awesome.com',
    'heading': 'I am awesome',
    'category': 'Awesome Junk'
  },
  'c101': {
    'url': 'https://coolstuff.com',
    'heading': 'How much cool stuff is there?',
    'category': 'Cool Junk n Stuff'
  },
  'c102': {
    'url': 'https://googleorsomething.com',
    'heading': 'Google is neat.',
    'category': 'Neat Junk'
  }
}

function GetURLParameter(sParam){
  var sPageURL = window.location.search.substring(1);
  var sURLVariables = sPageURL.split('&');
  for (var i = 0; i < sURLVariables.length; i++){
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam){
      return sParameterName[1];
    };
  };
};

// Set Up The Variables for Concatinating the String
var calcId = GetURLParameter('calc_id');
console.log(calcId);
var jsonObject = 'json.'+calcId+'.url';

$(function() {

  $('#dynamicContent').html(json.calcId.url);

});

Upvotes: 0

Views: 253

Answers (1)

Alexander
Alexander

Reputation: 23537

You can access an object property using [].

var calcId = GetURLParameter('calc_id');
var jsonObject = json[calcId]; 

$('#dynamicContent').html(jsonObject.url);

No concatenation is needed for this operation.

Upvotes: 1

Related Questions