0

I need to temporarily track the state of 5 objects in JavaScript. Each of these objects has a GUID as its id. Because of this, I was hoping to create an array of key/value pairs that I can work with. The key of each pair would be the id of each object. The value of each pair would be a boolean value. My problem is, I am really not sure how to do this in JavaScript. Currently, I have the following:

var myKeyValuePairs;

var myObjects = getMyObjects();
for (var i=0; i<myObjects.length; i++) {
  var id = myObjects[i].id;
  // What do I do now?
}

How do I build an array of key/value pairs in JavaScript?

JavaScript Developer
  • 3,968
  • 11
  • 41
  • 46
  • You can see answers to your problem in: http://stackoverflow.com/questions/130543/can-anyone-recommend-a-good-hashtable-implementation-in-javascript http://stackoverflow.com/questions/1208222/how-to-use-dictionary-or-hashtable-in-javascript – Dor Cohen Mar 13 '12 at 21:30

1 Answers1

8
var myKeyValuePairs = {},
    myObjects = getMyObjects(),
    i, obj

for (i=0, len = myObjects.length; i < len; i++) {
    obj = myObjects[i]
    myKeyValuePairs[obj.id] = obj
}

Or if you really want to use an array you could do something like

var myKeyValuePairs = getMyObjects.map(function (obj) {
    return {
        key: obj.id,
        value: obj
    }
})
Raynos
  • 166,823
  • 56
  • 351
  • 396