0

I am going to use an object as a HashMap in JavaScript. I want to add a key which would be a new property for that object and give it a value. Then, after a while, take that value and do stuff on that.

I want to extract all the links. Save the URL of the page as the key and the array of its links as the value. Therefore, I have wrote following lines.

let's say the URL of the page is http://www.google.com

var test = {};
var links = document.getElementsByTagName('a');
var currentURL = document.URL;
test.currentURL = links;

Here, my expectation was that I have a key which is http://www.google.com together with its value which is an array contains all the links on the page. After that, I wanted to write following line

var inProcessURL = allTheURLs[0].url;
var arrayOfLinks = test.inProcessURL;

and then work based on this array. But, I found that in the first part, I am creating the key which is 'currentURL' not 'http://www.google.com' which causes me to not be able to refer to it later on.

Is there any way based on which I can do my goal in JavaScript or I have to change my data structure from an Object to the Array?

I don't know which key I am going to refer to at different step. They would be something extracted from an array.

Suo6613
  • 431
  • 5
  • 17
  • 1
    possible duplicate of [How to create object property from variable value in javascript?](http://stackoverflow.com/questions/2241875/how-to-create-object-property-from-variable-value-in-javascript) – Paul Jan 29 '15 at 22:18

1 Answers1

0

First off, your variable links is a nodeList object which is a list of nodes. So, to reference a DOM object in that list, you would need to iterate through that list.

I'm not 100% sure I understand what you're trying to do, but if you want to iterate through all the links and create a hashmap of them by URL where the URL is the index and the data is the DOM object, you can do this:

var map = {};
var links = document.getElementsByTagName("a"), obj;
for (var i = 0; i < links.length; i++) {
    obj = links[i];
    map[obj.href] = obj;
}

This allows you to index into the map by URL to fetch the DOM object that links to that URL. Note: if you have any links that contain the same URL as other links, the map will contain the last DOM object that references that URL since maps don't by themselves support duplicates.

So, if you then want to find which DOM object links to the link in a particular variable, you can do that like this:

var url = "http://www.google.com";
var obj = map[url];

Keep in mind that this map is not in any particular order (you would need an array if you want order to be preserved). You can index into the map as in the above line or you can iterate all the URLs in the map like this:

for (var url in map) {
    // url is the URL, map[url] is the DOM object for that URL
    if (url === "http://www.google.com") {
        map[url].style.color = "red";
    }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979