How to create Dictionary [Key : value] in jQuery

dictionary, html, javascript, jquery

Solution

Use an object:

var obj = {};
$(".people-autocomplete").each(function() {
    obj[$(this).attr('id')] = $(this).attr('parent');
});

You can then access the parent of a specific `id`:

var parent = obj.idName;

or through a string:

var idStr = 'idName';
var parent = obj[idStr];

And you can loop through:

for (idStr in obj) {
    var parent = obj[idStr];
}

Problem

I have a input elements in html with two important attributes: id, and parentElementId. I want to create a map/dictionary that looks like this: "id : parentElementId". ``` var parent = $(".people-autocomplete").map( function(){ return $(this).attr('id')+':'+$(this).attr('parent'); }).get() ; ``` for know I'm putting the values into a string, which I parse later on in the code. I presume there is a more elegant solution than this.

Original source