0

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);

});

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.