2

I have an array named territory which contains the following

enter image description here

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

thankyou for the quick reply ,but how do i handle duplicate id's , if i occur duplicate id's i want to do a summation and enter only one entry for that id
if you get the same id twice, with this code, it's gonna go to the key x and override inside previous data... that's it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.