2

I want to use Javascript object as a key in the hashmap. In order to do this, I have to convert this Javascript object into the string. There also has to be a way to decode the object back from this string.

What is the best way of doing this?

So far I have found two ways of converting it. Using JQuery Params method and JSON.stringify.

Thanks.

2
  • JSON: developer.mozilla.org/en-US/docs/JSON. Assuming you are working with simple objects only. Commented Apr 10, 2014 at 0:04
  • ^ I have listed my research and asked for the better option whats wrong with that? Commented Apr 10, 2014 at 1:14

1 Answer 1

1

It seems JSON is what you need:

  • Object to string

    JSON.stringify(obj);
    
  • String to object

    JSON.parse(obj);
    

Or you could use ES6 Map in order to be able to directly use objects as keys, but currently browser support is small. Also note that different objects will be associated with different values, even if they look like the same:

var m = new Map(),
    obj1 = {}, obj2 = {};
m.set(obj1, 'foo');
m.set(obj2, 'bar');
m.get(obj1); // 'foo'
m.get(obj2); // 'bar'
Sign up to request clarification or add additional context in comments.

Comments

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.