Reputation: 2791
I have an array named territory which contains the following
i want to create a hashmap where the
key is the id [id atribute of each object wihin territory]
and the
value is the entire object
any help/pointers on the same?
thankyou
Upvotes: 2
Views: 8411
Reputation: 131
hi you could do like that and it will work :
var hashmap = {};
territory.forEach(function(element) {
if(hashmap[element.id]!==null && hashmap[element.id]!=undefined){
if(!Array.isArray(hashmap[element.id])){
var tempObj = hashmap[element.id];
// don't forget to json.stringify your object if you
// want to serialise your hashmap for external use
hashmap[element.id] = [tempObj];
}
hashmap[element.id].push(element);
}
else{
// if you want to serialise your hashmap for external use
hashmap[element.id] = JSON.stringify(element);
// if not, you could just do without JSON.stringify
hashmap[element.id] = element;
}
});
console.log(hashmap);
you could look at mozilla documentation for more informations on foreach
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Edit : I updated the code to avoid (dirty) id duplication and store object who share the same id
Upvotes: 2
Reputation: 48247
You simply need to iterate over the array and assign each element as a property in an object:
var hash = {};
var data = [...];
data.forEach(function (it) { hash[it.id] = it; });
If you have access to the lodash library, you can use indexBy
to transform the whole array at once:
var data = [...];
var hash = _.indexBy(data, 'id');
The underscore library also has an indexBy
method that behaves in the same fashion.
Upvotes: 5