0

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

or

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 !!!

slava
  • 1,901
  • 6
  • 28
  • 32
Tidus
  • 3
  • 2

1 Answers1

0

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];
// =============================

console.log(dataItem.value[0].name);
JonSG
  • 10,542
  • 2
  • 25
  • 36
  • this is awesome !!! exactly what i want. now I try to understand the specific spelling of the array. Thank you so much ! – Tidus Sep 29 '16 at 14:20