xralf
xralf

Reputation: 3762

Pythonic dictionary in Javascript

How would you implement pythonic dictionary in Javascript that is able to store key value pairs and key can be tuple?

I'd like to find all anchors and then store values of it's href and title attributes to dictionary as keys (href value, title value) and number of occurrencies of this tuple as a value.

The code would look like this (it's a mix of Python and Javascript):

var anchors = document.querySelectorAll ("a");
d = []; // dictionary data structure
for (var i = 0, len = anchors.length; i < len; i++) {
  currentTuple = (anchors[i].href, anchors[i].title);
  if (!d.containsKey(currentTuple)) {
    d[currentTuple] = 1;
  } else {
   d[currentTuple] += 1;
  }
}

Maybe it would be easier if keys couldn't be tuples, but if it's possible i'd like to see it.

thank you

Upvotes: 0

Views: 133

Answers (1)

Esailija
Esailija

Reputation: 140236

Could this work? It just concatenates title and href as a unique key.

var data = [].reduce.call( document.links, function( data, a){
    var key = a.href+","+a.title;
    if( data[key] ) {
        data[key]++;
    }
    else {
        data[key] = 1;
    }   

return data;
}, {} );

http://jsfiddle.net/knYwb/

Upvotes: 1

Related Questions