sublime
sublime

Reputation: 4161

encode and decode javascript objects to and from the string

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.

Upvotes: 2

Views: 6188

Answers (1)

Oriol
Oriol

Reputation: 287960

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'

Upvotes: 1

Related Questions