Tidus Tidus - 1 year ago 48
JSON Question

javascript use url as string for array

i have an external .js with arrays.

test = [
"name": "1"
test2 = [
"name": "2"

now I want to use the url to identify the name of the array.
So if someone goes on test.html he is using the test array and test2.html test2 array.

if i use

var queryArray = window.location.search.substring(1);


var queryArray = window.location.href

or something like this and then

document.getElementById("demo").innerHTML = queryArray.name;

it doesn't work, because he is of course looking for the array queryArray which one doesn't exist.
Is there a way to use the url as an identifier?

I hope You can understand the point ^^

THX for every idea !!!

Answer Source

If you have the ability to slightly restructure the way you specify the "arrays" you might do something like this:

// =============================
// Similar but a little more tidy
// This also supports file names with characters like "-" or complete url strings
// =============================
var dataItems = [
  {key : "test1", value: [{"name": "This is test 1"}]},
  {key : "test2", value: [{"name": "This is test 2"}]},
  {key : "js", value: [{"name": "This is the sandbox"}]} // This sandbox (I think)
// =============================

// =============================
// You migth now use the full pathname as the data item key,
// but if you wanted to use the "name" of the file you might do something like this.
// =============================
var currentFileName = location.pathname.split("/").pop().split(".html")[0];
// =============================

// =============================
// You might want to do this in several steps to handle stuff like filter returning
// no hits.
// =============================
var dataItem = dataItems.filter(function(item){ return item.key === currentFileName;})[0];
// =============================