Deserialize JSON into specific/existing JavaScript object - javascript

Is there a way to parse a JSON string into an existing Javascript object:
Lets say i have created this object:
var ClientState = function(){
this.userId ="";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
ClientState.prototype = {
doNastyStuff: function(){
//do something here
}
//other methods here
}
I have this json coming through the wire:
{"userId":"xyz","telephoneState":"READY","agentState":"UNKNOWN","muteState":"MUTED","number":"","ready":false}
Is it possible to deserialize into the object specified above? So that i can use all methods specified on it?
Or in general is it possible to deserialize into a specific target object (without specifying deserialization in this target object)?
(I know that i could create an constructor that accepts json or a parsed object.)

Yes! You can use Object.assign to overwrite the attributes of an object with another object:
var ClientState = function() {
this.userId = "";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
var c = new ClientState();
console.log('prior assignment: ', c);
Object.assign(c, {
"userId": "xyz",
"telephoneState": "READY",
"agentState": "UNKNOWN",
"muteState": "MUTED",
"number": "",
"ready": false
});
console.log('after assignment: ', c);
Note that it will overwrite all the properties of source object (first object) with the target object (second object) by matching the respective keys. The keys, which are non-existing in the target object are left intact in the source object.

Is this what you had in mind?
function parseAs(targetClass, rawJSON) {
return Object.assign(new targetClass(), JSON.parse(rawJSON));
}
var clientState = parseAs(ClientState, '{"userId":"xyz"}');
I don't think there's a native JSON method that does this, but you can just write a function like the one above. You can even define it on the JSON class itself:
JSON.parseAs = function(targetClass, rawJSON) {
return Object.assign(new targetClass(), JSON.parse(rawJSON));
}

If you want to use your function to add the object values to the instance properties:
function ClientState() {
this.userId = "";
this.telephoneState = "UNKNOWN";
this.agentState = "UNKNOWN";
this.muteState = "UNKNOWN";
this.number = "";
this.ready = false;
}
ClientState.prototype = {
doNastyStuff: function(json) {
const data = JSON.parse(json);
Object.assign(this, data);
}
}
const json = '{"userId":"xyz","telephoneState":"READY","agentState":"UNKNOWN","muteState":"MUTED","number":"","ready":false}';
const clientState = new ClientState();
clientState.doNastyStuff(json);
console.log(clientState);

Related

Make json from array of objects javascript

I have a javascript object with a lot of attributes and methods, I want it to be sent to a php file. For this, I want to transform it to Json data.
But I just can`t understand how should I use json.stringify to do this, because of the complex object's class.
The objects looks like this. I have an array of objects that I have to sent over ajax.
Also, this class has array of other objects as attributes, and a bunch of other methods.
var PhotoFile = function(clientFileHandle){
PhotoFile.count = PhotoFile.count + 1;
this.specificClass = "no-" + PhotoFile.count;
this.checkbox = null;
this.attributes = [];
this.file = clientFileHandle;
this.fileExtension = null;
//meta data
this.meta = null;
this.orientation = null;
this.oDateTime = null;
this.maxWidth = 150;
this.maxHeight = 100;
//raw data
this.imgData = null;
this.imgDataWidth = null;
this.imgDataHeight = null;
this.checkSum1 = null;
this.checkSum2 = null;
//DOM stuff
this.domElement = null;
this.imgElement = null;
this.loadProgressBar = null;
this.uploadProgressBar = null;
this.imageContainer = null;
this.attributeContainer = null;
this.indexInGlobalArray = -1;
//flags
this.metaLoaded = false;
this.startedLoading = false;
this.finishedLoading = false;
this.needsUploading = true;
this.imageDisplayed = false;
//listeners
this.onFinishedLoading = function () {};
this.onFinishedUploading = function () {console.log('Called default end '+this.file.name)};
..... plus other methods.
}
You could create a function on your object that returns a serializable representation of your object.
E.g.
function SomeObject() {
this.serializeThis = 'serializeThis';
this.dontSerializeThis = 'dontSerializeThis';
}
SomeObject.prototype.toSerializable = function () {
//You can use a generic solution like below
return subsetOf(this, ['serializeThis']);
//Or a hard-coded version
// return { serializeThis: this.serializeThis };
};
//The generic property extraction algorithm would need to be more complex
//to deep-filter objects.
function subsetOf(obj, props) {
return (props || []).reduce(function (subset, prop) {
subset[prop] = obj[prop];
return subset;
}, {});
}
var o = new SomeObject();
JSON.stringify(o.toSerializable()); //{"serializeThis":"serializeThis"}
Note that using a generic property extractor algorithm would force you to leak implementation details and therefore, violate encapsulation so although it might be shorter to implement a solution using this method, it might not be the best way in some cases.
However, one thing that can usually be done to limit internals leakage is to implement property getters.

how to get the content of java script object in another object?

how to get the content of java script object in another object ?
let say my variable are like follows :
var credentials ={
"name":userName,
"passwd":password
}
var params={
"Credentials":credentials
}
am passing params as an parameter to same other function.In that function i have another object pkt ,as follows :
var pkt={
"name":xxx,
//XXXX
}
what to code at XXXX so that my final pkt structure should be like:
pkt={
"name":xxx,
"Credentials": {
"name":userName,
"passwd":password
}
}
we may have multiple objects inside params,the requirement is that the key value pair should come accordingly.
the equivalent java code is as follows:
Iterator iterKeys = params.keySet().iterator();
while (iterKeys.hasNext())
{
String key = (String)iterKeys.next();
JSONValue value = params.get(key);
pkt.put(key, value);
}
Thanks.
Javascript objects are just Hashmaps.
var credentials = {
"name": "userName",
"passwd": "password"
}
var params = {
"Credentials": credentials
}
var pkt = {
"name": "xxx",
}
for (var property in params) {
if (params.hasOwnProperty(property)) {
var value = property;
pkt[property] = params[property];
}
}
alert(JSON.stringify(pkt));
You can just assign as seen in [this fiddle]
(http://jsfiddle.net/TfWMy/)
You could use a library function like $.extend or _.extend:
pkt = $.extend(pkt, params);
Otherwise you can loop through params and add each key/value pair to pkt:
for (var key in params){
pkt[key] = params[key];
}
Use hasOwnProperty to avoid looping over ancestor members.
You can also use associative array structure.
i.e
var credentials = {
"name": "userName",
"passwd": "password"
}
var pkt = {
"name": "xxx",
}
pkt["Credentials"] = credentials
Not particularly sure about this, but this should work as expected.
Here's two quick functions that should do what you're looking for. The first adds the keys and values to a new object, the second function adds the keys and values to the first object.
var mergeObjectsToNew = function(o1, o2) {
var r = {};
for (var key in o1) {
r[key] = o1[key];
}
for (var key in o2) {
r[key] = o2[key];
}
return r;
}
var mergeObjects = function(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}
I think you are looking to extend your object with another.
Please follow the code and I hope this is the thing you are require.
var credentials ={
"name":"",
"passwd":""
}
var params={
"Credentials":credentials
}
var pkt={
name:"ABC"
};
function Extends(param1,param2){
var object = $.extend({}, param1, param2);
console.log(object);
}
Extends(params,pkt);
Please find Fiddle Below
Fiddle

Stackoverflow error on Javascript toJSON custom method

Scenario
After reading this answer I realized that I could create object starting from a JSON literal.
So I guessed that I could do the opposite just using this useful JSON method:
JSON.stringify(myObject).
So I did as follow:
function MyObject(id, value, desc)
{
this.id = id;
this.value = value;
this.desc = desc;
this.toJSON = function()
{
return JSON.stringify(this);
}
}
But when I run this stuff (demo) a Maximum call stack size exceeded error occurs.
After googling a bit, I found two references that explain this behaviour:
the JSON.stringify() method at MDN.
the JSON in Javascript article at JSON.org
If I get right, .toJSON overrides the .stringify. So if the first one calls the second one a loop is generated.
Questions
(general) Why this design choice? toJSON is a kind of reserved of special keyword?
(specific) I solved the stackoverflow bug changing the .toJSON name into .display. Not so elegant. Is there another solution?
Think it's because toJSON is semi reserved: stringify will check the object and see if it's has a method called toJSON and then try to call it to string the result.
A workaround can be: (Not sure about the reliablity of this code)
var obj = {
value: 1,
name: "John",
toJSON: function() {
var ret,
fn = this.toJSON;
delete this.toJSON;
ret = JSON.stringify(this);
this.toJSON = fn;
return ret;
}
}
Usage:
obj.toJSON(); // "{\"value\":1,\"name\":\"John\"}"
obj.lastName = "Smith";
obj.toJSON(); // "{\"value\":1,\"name\":\"John\",\"lastName\":\"Smith\"}"
Maybe using a clousure is a little prettier: (And then I think I can say it's safe)
var obj = {
value: 1,
name: "John",
toJSON: (function() {
function fn() {
var ret;
delete this.toJSON;
ret = JSON.stringify(this);
this.toJSON = fn;
return ret;
}
return fn;
})()
}
So after reading #filmor's comment i thoght about another way to handle this. Not that pretty but it works.
Using Function.caller I can detect if fn is called using JSON.stringify
var obj = {
value: 1,
name: "John",
toJSON: (function() {
return function fn() {
var ret;
delete this.toJSON;
ret = JSON.stringify(this);
if ( fn.caller === JSON.stringify ) {
ret = JSON.parse( ret );
}
this.toJSON = fn;
return ret;
}
})()
}
Question 1, is toJSON reserved?
I'm not sure if it reserved, but for example the native Date object uses toJSON to create a stringified date representation:
(new Date()).toJSON(); // -> "2012-10-20T01:58:21.427Z"
JSON.stringify({d: new Date()}); // -> {"d":"2012-10-20T01:58:21.427Z"}"
Question 2, an easy solution:
create your custom stringify function that ignores toJSON methods (you may add it to the already existing global JSON):
JSON.customStringify = function (obj) {
var fn = obj.toJSON;
obj.toJSON = undefined;
var json = JSON.stringify(obj);
obj.toJSON = fn;
return json;
}
now it's very easy to use in all your objects:
function MyObject(id, value, desc)
{
this.id = id;
this.value = value;
this.desc = desc;
this.toJSON = function()
{
return JSON.customStringify(this);
}
}
To make it even more easy additionally add:
JSON.customStringifyMethod = function () {
return JSON.customStringify(this);
}
Now your objects might look like:
function MyObject(id, value, desc)
{
this.id = id;
this.value = value;
this.desc = desc;
this.toJSON = JSON.customStringifyMethod;
}

Parse JSON String into a Particular Object Prototype in JavaScript

I know how to parse a JSON String and turn it into a JavaScript Object.
You can use JSON.parse() in modern browsers (and IE9+).
That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?
For example, suppose you have:
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
Again, I am not wondering how to convert a JSON string into a generic JavaScript Object. I want to know how to convert a JSON string into a "Foo" Object. That is, my Object should now have a function 'test' and properties 'a' and 'b'.
UPDATE
After doing some research, I thought of this...
Object.cast = function cast(rawObj, constructor)
{
var obj = new constructor();
for(var i in rawObj)
obj[i] = rawObj[i];
return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);
Will that work?
UPDATE May, 2017: The "modern" way of doing this, is via Object.assign, but this function is not available in IE 11 or older Android browsers.
The current answers contain a lot of hand-rolled or library code. This is not necessary.
Use JSON.parse('{"a":1}') to create a plain object.
Use one of the standardized functions to set the prototype:
Object.assign(new Foo, { a: 1 })
Object.setPrototypeOf({ a: 1 }, Foo.prototype)
See an example below (this example uses the native JSON object). My changes are commented in CAPITALS:
function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
// IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
for (var prop in obj) this[prop] = obj[prop];
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));
alert(fooJSON.test() ); //Prints 12
Do you want to add JSON serialization/deserialization functionality, right? Then look at this:
You want to achieve this:
toJson() is a normal method.
fromJson() is a static method.
Implementation:
var Book = function (title, author, isbn, price, stock){
this.title = title;
this.author = author;
this.isbn = isbn;
this.price = price;
this.stock = stock;
this.toJson = function (){
return ("{" +
"\"title\":\"" + this.title + "\"," +
"\"author\":\"" + this.author + "\"," +
"\"isbn\":\"" + this.isbn + "\"," +
"\"price\":" + this.price + "," +
"\"stock\":" + this.stock +
"}");
};
};
Book.fromJson = function (json){
var obj = JSON.parse (json);
return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};
Usage:
var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}
var book = Book.fromJson (json);
alert (book.title); //prints: t
Note: If you want you can change all property definitions like this.title, this.author, etc by var title, var author, etc. and add getters to them to accomplish the UML definition.
A blog post that I found useful:
Understanding JavaScript Prototypes
You can mess with the __proto__ property of the Object.
var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
fooJSON.__proto__ = Foo.prototype;
This allows fooJSON to inherit the Foo prototype.
I don't think this works in IE, though... at least from what I've read.
Am I missing something in the question or why else nobody mentioned reviver parameter of JSON.parse since 2011?
Here is simplistic code for solution that works:
https://jsfiddle.net/Ldr2utrr/
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse(`{"a":4, "b": 3}`, function(key,value){
if(key!=="") return value; //logic of course should be more complex for handling nested objects etc.
let res = new Foo();
res.a = value.a;
res.b = value.b;
return res;
});
// Here you already get Foo object back
alert(fooJSON.test() ); //Prints 12
PS: Your question is confusing: >>That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?
contradicts to the title, where you ask about JSON parsing, but the quoted paragraph asks about JS runtime object prototype replacement.
The currently accepted answer wasn't working for me. You need to use Object.assign() properly:
class Person {
constructor(name, age){
this.name = name;
this.age = age;
}
greet(){
return `hello my name is ${ this.name } and i am ${ this.age } years old`;
}
}
You create objects of this class normally:
let matt = new Person('matt', 12);
console.log(matt.greet()); // prints "hello my name is matt and i am 12 years old"
If you have a json string you need to parse into the Person class, do it like so:
let str = '{"name": "john", "age": 15}';
let john = JSON.parse(str); // parses string into normal Object type
console.log(john.greet()); // error!!
john = Object.assign(Person.prototype, john); // now john is a Person type
console.log(john.greet()); // now this works
An alternate approach could be using Object.create. As first argument, you pass the prototype, and for the second one you pass a map of property names to descriptors:
function SomeConstructor() {
};
SomeConstructor.prototype = {
doStuff: function() {
console.log("Some stuff");
}
};
var jsonText = '{ "text": "hello wrold" }';
var deserialized = JSON.parse(jsonText);
// This will build a property to descriptor map
// required for #2 argument of Object.create
var descriptors = Object.keys(deserialized)
.reduce(function(result, property) {
result[property] = Object.getOwnPropertyDescriptor(deserialized, property);
}, {});
var obj = Object.create(SomeConstructor.prototype, descriptors);
I like adding an optional argument to the constructor and calling Object.assign(this, obj), then handling any properties that are objects or arrays of objects themselves:
constructor(obj) {
if (obj != null) {
Object.assign(this, obj);
if (this.ingredients != null) {
this.ingredients = this.ingredients.map(x => new Ingredient(x));
}
}
}
For the sake of completeness, here's a simple one-liner I ended up with (I had no need checking for non-Foo-properties):
var Foo = function(){ this.bar = 1; };
// angular version
var foo = angular.extend(new Foo(), angular.fromJson('{ "bar" : 2 }'));
// jquery version
var foo = jQuery.extend(new Foo(), jQuery.parseJSON('{ "bar" : 3 }'));
I created a package called json-dry. It supports (circular) references and also class instances.
You have to define 2 new methods in your class (toDry on the prototype and unDry as a static method), register the class (Dry.registerClass), and off you go.
While, this is not technically what you want, if you know before hand the type of object you want to handle you can use the call/apply methods of the prototype of your known object.
you can change this
alert(fooJSON.test() ); //Prints 12
to this
alert(Foo.prototype.test.call(fooJSON); //Prints 12
I've combined the solutions that I was able to find and compiled it into a generic one that can automatically parse a custom object and all it's fields recursively so you can use prototype methods after deserialization.
One assumption is that you defined a special filed that indicates it's type in every object you want to apply it's type automatically (this.__type in the example).
function Msg(data) {
//... your init code
this.data = data //can be another object or an array of objects of custom types.
//If those objects defines `this.__type', their types will be assigned automatically as well
this.__type = "Msg"; // <- store the object's type to assign it automatically
}
Msg.prototype = {
createErrorMsg: function(errorMsg){
return new Msg(0, null, errorMsg)
},
isSuccess: function(){
return this.errorMsg == null;
}
}
usage:
var responseMsg = //json string of Msg object received;
responseMsg = assignType(responseMsg);
if(responseMsg.isSuccess()){ // isSuccess() is now available
//furhter logic
//...
}
Type assignment function (it work recursively to assign types to any nested objects; it also iterates through arrays to find any suitable objects):
function assignType(object){
if(object && typeof(object) === 'object' && window[object.__type]) {
object = assignTypeRecursion(object.__type, object);
}
return object;
}
function assignTypeRecursion(type, object){
for (var key in object) {
if (object.hasOwnProperty(key)) {
var obj = object[key];
if(Array.isArray(obj)){
for(var i = 0; i < obj.length; ++i){
var arrItem = obj[i];
if(arrItem && typeof(arrItem) === 'object' && window[arrItem.__type]) {
obj[i] = assignTypeRecursion(arrItem.__type, arrItem);
}
}
} else if(obj && typeof(obj) === 'object' && window[obj.__type]) {
object[key] = assignTypeRecursion(obj.__type, obj);
}
}
}
return Object.assign(new window[type](), object);
}
A very simple way to get the desired effect is to add an type attribute while generating the json string, and use this string while parsing the string to generate the object:
serialize = function(pObject) {
return JSON.stringify(pObject, (key, value) => {
if (typeof(value) == "object") {
value._type = value.constructor.name;
}
return value;
});
}
deSerialize = function(pJsonString) {
return JSON.parse(pJsonString, (key, value) => {
if (typeof(value) == "object" && value._type) {
value = Object.assign(eval('new ' + value._type + '()'), value);
delete value._type;
}
return value;
});
}
Here a little example of use:
class TextBuffer {
constructor() {
this.text = "";
}
getText = function() {
return this.text;
}
setText = function(pText) {
this.text = pText;
}
}
let textBuffer = new TextBuffer();
textBuffer.setText("Hallo");
console.log(textBuffer.getText()); // "Hallo"
let newTextBuffer = deSerialize(serialize(textBuffer));
console.log(newTextBuffer.getText()); // "Hallo"
Here is a solution using typescript and decorators.
Objects keep their methods after deserialization
Empty objects and their children are default-initialized
How to use it:
#SerializableClass
class SomeClass {
serializedPrimitive: string;
#SerializableProp(OtherSerializedClass)
complexSerialized = new OtherSerializedClass();
}
#SerializableClass
class OtherSerializedClass {
anotherPrimitive: number;
someFunction(): void {
}
}
const obj = new SomeClass();
const json = Serializable.serializeObject(obj);
let deserialized = new SomeClass();
Serializable.deserializeObject(deserialized, JSON.parse(json));
deserialized.complexSerialized.someFunction(); // this works!
How it works
Serialization:
Store the type name in the prototype (__typeName)
Use JSON.stringify with a replacer method that adds __typeName to the JSON.
Deserialization:
Store all serializable types in Serializable.__serializableObjects
Store a list of complex typed properties in every object (__serializedProps)
Initialize an object theObject via the type name and __serializableObjects.
Go through theObject.__serializedProps and traverse over it recursively (start at last step with every serialized property). Assign the results to the according property.
Use Object.assign to assign all remaining primitive properties.
The code:
// #Class decorator for serializable objects
export function SerializableClass(targetClass): void {
targetClass.prototype.__typeName = targetClass.name;
Serializable.__serializableObjects[targetClass.name] = targetClass;
}
// #Property decorator for serializable properties
export function SerializableProp(objectType: any) {
return (target: {} | any, name?: PropertyKey): any => {
if (!target.constructor.prototype?.__serializedProps)
target.constructor.prototype.__serializedProps = {};
target.constructor.prototype.__serializedProps[name] = objectType.name;
};
}
export default class Serializable {
public static __serializableObjects: any = {};
private constructor() {
// don't inherit from me!
}
static serializeObject(typedObject: object) {
return JSON.stringify(typedObject, (key, value) => {
if (value) {
const proto = Object.getPrototypeOf(value);
if (proto?.__typeName)
value.__typeName = proto.__typeName;
}
return value;
}
);
}
static deserializeObject(typedObject: object, jsonObject: object): object {
const typeName = typedObject.__typeName;
return Object.assign(typedObject, this.assignTypeRecursion(typeName, jsonObject));
}
private static assignTypeRecursion(typeName, object): object {
const theObject = new Serializable.__serializableObjects[typeName]();
Object.assign(theObject, object);
const props = Object.getPrototypeOf(theObject).__serializedProps;
for (const property in props) {
const type = props[property];
try {
if (type == Array.name) {
const obj = object[property];
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; ++i) {
const arrItem = obj[i];
obj[i] = Serializable.assignTypeRecursion(arrItem.__typeName, arrItem);
}
} else
object[property] = [];
} else
object[property] = Serializable.assignTypeRecursion(type, object[property]);
} catch (e) {
console.error(`${e.message}: ${type}`);
}
}
return theObject;
}
}
Comments
Since I am a total js/ts newby (< 10 days), I am more than happy to receive any input/comments/suggestions. Here are some of my thoughts so far:
It could be cleaner: Unfortunately I did not find a way to get rid of the redundant parameter of #SerializableProp.
It could be more memory friendly: After you call serializeObject() every object stores __typeName which could massively blow up memory footprint. Fortunately __serializedProps is only stored once per class.
It could be more CPU friendly: It's the most inefficient code I've ever written. But well, it's just for web apps, so who cares ;-) Maybe one should at least get rid of the recursion.
Almost no error handling: well that's a task for another day
class A {
constructor (a) {
this.a = a
}
method1 () {
console.log('hi')
}
}
var b = new A(1)
b.method1() // hi
var c = JSON.stringify(b)
var d = JSON.parse(c)
console.log(d.a) // 1
try {
d.method1() // not a function
} catch {
console.log('not a function')
}
var e = Object.setPrototypeOf(d, A.prototype)
e.method1() // hi
Olivers answers is very clear, but if you are looking for a solution in angular js, I have written a nice module called Angular-jsClass which does this ease, having objects defined in litaral notation is always bad when you are aiming to a big project but saying that developers face problem which exactly BMiner said, how to serialize a json to prototype or constructor notation objects
var jone = new Student();
jone.populate(jsonString); // populate Student class with Json string
console.log(jone.getName()); // Student Object is ready to use
https://github.com/imalhasaranga/Angular-JSClass

Do the keys of JavaScript associative arrays need to be strings, or can they be any object?

Do the keys of JavaScript associative arrays need to be strings, or can they be any object?
There are no native associative arrays in JavaScript, only objects. Objects have properties. The names of properties are always strings: even the numeric indices of arrays will be converted to strings before the 'array magic' happens.
If you're looking for associative arrays with arbitrary keys, look here.
I've implemented JavaScript HashMap which code can be obtained from http://github.com/lambder/HashMapJS/tree/master
The keys and values can be arbitrary JavaScript objects.
There aren't any requirements on objects used as keys or values.
The mechanism is trivial. For every key there is generated a unique id (per HashMap instance).
That id is injected to the key object under a high unlikely to collide field name ;)
That id is then used to keying in the underlying baking standard JavaScript association object.
Here is the code:
/*
=====================================================================
#license MIT
#author Lambder
#copyright 2009 Lambder.
#end
=====================================================================
*/
var HashMap = function() {
this.initialize();
}
HashMap.prototype = {
hashkey_prefix: "<#HashMapHashkeyPerfix>",
hashcode_field: "<#HashMapHashkeyPerfix>",
initialize: function() {
this.backing_hash = {};
this.code = 0;
},
/*
Maps value to key, returning the previous association
*/
put: function(key, value) {
var prev;
if (key && value) {
var hashCode = key[this.hashcode_field];
if (hashCode) {
prev = this.backing_hash[hashCode];
} else {
this.code += 1;
hashCode = this.hashkey_prefix + this.code;
key[this.hashcode_field] = hashCode;
}
this.backing_hash[hashCode] = value;
}
return prev;
},
/*
Returns value associated with given key
*/
get: function(key) {
var value;
if (key) {
var hashCode = key[this.hashcode_field];
if (hashCode) {
value = this.backing_hash[hashCode];
}
}
return value;
},
/*
Deletes association by given key.
Returns true if the association existed, false otherwise
*/
del: function(key) {
var success = false;
if (key) {
var hashCode = key[this.hashcode_field];
if (hashCode) {
var prev = this.backing_hash[hashCode];
this.backing_hash[hashCode] = undefined;
if(prev !== undefined)
success = true;
}
}
return success;
}
}
//// Usage
// Creation
var my_map = new HashMap();
// Insertion
var a_key = {};
var a_value = {struct: "structA"};
var b_key = {};
var b_value = {struct: "structB"};
var c_key = {};
var c_value = {struct: "structC"};
my_map.put(a_key, a_value);
my_map.put(b_key, b_value);
var prev_b = my_map.put(b_key, c_value);
// Retrieval
if(my_map.get(a_key) !== a_value){
throw("fail1")
}
if(my_map.get(b_key) !== c_value){
throw("fail2")
}
if(prev_b !== b_value){
throw("fail3")
}
// Deletion
var a_existed = my_map.del(a_key);
var c_existed = my_map.del(c_key);
var a2_existed = my_map.del(a_key);
if(a_existed !== true){
throw("fail4")
}
if(c_existed !== false){
throw("fail5")
}
if(a2_existed !== false){
throw("fail6")
}
Are you talking about JavaScript objects (JSON)?
The specification says that the keys should be strings.
But the JavaScript interpreter allows both {"key": "val"} and {key: "val"}.
Building on Lambder's idea, I've implemented a small DataStructures library.
I've tested it a little and everything seems to work.
It also automatically assigns a unique id to each HashTable/HashSet used to uniquely identify the object's key property.
var DataStructure = {};
DataStructure.init = function(){
DataStructure.initHashables();
delete DataStructure.initHashables;
}
DataStructure.initHashables = function(){
var objectHashableIndexer = new DataStructure.Indexer();
DataStructure.Hashable = function(){
var self = this;
// Constant
//
//
const ERROR_KEY_DOES_NOT_EXIST = "Key doesn't exists in Hashable when trying to pop. Associated Key Object and Hashable logged to console.";
const HASH_MAP_KEY_PROPERTY_BASE = "DATA_STRUCTURE_HASH_MAP_KEY_PROPERTY_";
// Attributes
//
//
var tableNumber = objectHashableIndexer.getIndex();
var tableKeyProperty = HASH_MAP_KEY_PROPERTY_BASE + tableNumber.toString();
self.tableKeyProperty = tableKeyProperty;
var indexer = new DataStructure.Indexer();
var data = {};
self.data = data;
// Methods
//
//
self.getObjectKey = function(){
return indexer.getIndex().toString();
}
self.putBackObjectKey = function(index){
indexer.putBackIndex(parseInt(index));
}
var getObjectKey = self.getObjectKey;
var putBackObjectKey = self.putBackObjectKey;
self.exists = function(key){
if (!(tableKeyProperty in key))
return false;
var realKey = key[tableKeyProperty];
if (!(realKey in data))
return false;
return true;
}
self.pop = function(key){
if (!self.exists(key)){
console.log(key);
console.log(self);
throw ERROR_KEY_DOES_NOT_EXIST;
}
else{
var realKey = key[tableKeyProperty];
delete key[tableKeyProperty];
delete data[realKey];
putBackObjectKey(realKey);
}
}
self.destroy = function(){
objectHashableIndexer.putBackIndex(tableNumber);
delete self;
}
}
/*
Class DataStructure.ObjectHashMap
Purpose: Provides a way to hash arbitrary objects to values.
Prototype Arguments:
Attributes:
Methods:
Notes:
Should call inherited method destroy() when done with table to preserve indexes
*/
DataStructure.ObjectHashMap = function(){
DataStructure.Hashable.call(this);
var self = this;
// Constant
//
//
const ERROR_KEY_EXISTS = "Key already exists in ObjectHashMap when trying to push. Associated Key Object and ObjectHashMap logged to console.";
const ERROR_KEY_DOES_NOT_EXIST = "Key doesn't exists in ObjectHashMap when trying to getValue. Associated Key Object and ObjectHashMap logged to console.";
// Attributes
//
//
var tableKeyProperty;
var data;
// Initialization
//
//
self.init = function(){
self.privatize();
delete self.privatize;
}
self.privatize = function(){
tableKeyProperty = self.tableKeyProperty;
delete self.tableKeyProperty;
getObjectKey = self.getObjectKey;
delete self.getObjectKey;
putBackObjectKey = self.putBackObjectKey;
delete self.putBackObjectKey;
data = self.data;
delete self.data;
}
// Methods
//
//
var getObjectKey;
var putBackObjectKey;
self.push = function(key, value){
if (self.exists(key)){
console.log(key);
console.log(self);
throw ERROR_KEY_EXISTS;
}
else{
var realKey = getObjectKey();
key[tableKeyProperty] = realKey;
data[realKey] = value;
}
}
self.getValue = function(key){
if(!self.exists(key)){
console.log(key);
console.log(self);
throw ERROR_KEY_DOES_NOT_EXIST;
}
else{
var realKey = key[tableKeyProperty];
return data[realKey];
}
}
self.init();
delete self.init;
}
/*
Class DataStructure.ObjectHashSet
Purpose: Provides a way to store arbitrary objects and check that they exist.
Prototype Arguments:
Attributes:
Methods:
Notes:
Should call inherited method destroy() when done with table to preserve indexes
*/
DataStructure.ObjectHashSet = function(){
DataStructure.Hashable.call(this);
var self = this;
// Constant
//
//
const ERROR_KEY_EXISTS = "Key already exists in ObjectHashSet when trying to push. Associated Key Object and ObjectHashSet logged to console.";
const ERROR_KEY_DOES_NOT_EXIST = "Key doesn't exists in ObjectHashSet when trying to getValue. Associated Key Object and ObjectHashSet logged to console.";
// Attributes
//
//
var tableKeyProperty;
var data;
// Initialization
//
//
self.init = function(){
self.privatize();
delete self.privatize;
}
self.privatize = function(){
tableKeyProperty = self.tableKeyProperty;
delete self.tableKeyProperty;
getObjectKey = self.getObjectKey;
delete self.getObjectKey;
putBackObjectKey = self.putBackObjectKey;
delete self.putBackObjectKey;
data = self.data;
delete self.data;
}
// Methods
//
//
var getObjectKey;
var putBackObjectKey;
self.push = function(key){
if (self.exists(key)){
console.log(key);
console.log(self);
throw ERROR_KEY_EXISTS;
}
else{
var realKey = getObjectKey();
key[tableKeyProperty] = realKey;
data[realKey] = "";
}
}
self.init();
delete self.init;
}
}
DataStructure.Indexer = function(){
var self = this;
// Constant
//
//
const DEFAULT_SIZE = 1000;
// Attributes
//
//
var nextIndex = 0;
var availableIndicies = 0;
var freeIndicies = [];
// Initialization
//
//
self.init = function(){
freeIndicies.length = DEFAULT_SIZE;
}
// Methods
//
//
self.getIndex = function(){
var index = 0;
if (availableIndicies === 0){
index = nextIndex;
++nextIndex;
}
else{
--availableIndicies;
index = freeIndicies[availableIndicies];
}
return index;
}
self.putBackIndex = function(index){
if (availableIndicies === freeIndicies.length)
freeIndicies.push(index);
else
freeIndicies[availableIndicies] = index;
++availableIndicies;
}
self.init();
delete self.init;
}
DataStructure.init();
delete DataStructure.init;
It depends on what you mean by "associative arrays". There is nothing called "associative arrays" in JavaScript, there are objects and there are maps.
Objects are the ones that can be accessed using the [] notation, for example foo["bar"], and there the keys have to be strings, as Christoph's answer explains.
There are also maps, which can have any object as keys. However, to access them, you can't use [] as for objects, you must use the get and set methods. Here is an example how to use them:
let myMap = new Map(); // Create the map
myMap.set("key", "value"); // To set a value, use the set method.
// The first argument is the key, the second one is the value.
myMap.set(Math, "bar"); // You can really use any object as key
myMap.set(console.log, "hello"); // Including functions
myMap.set(document.body, "world"); // And even DOM elements
// To get the value associated to a key, use the get method
console.log(myMap.get(Math)); // "bar"
console.log(myMap.get(document.body)); // "world"
In this example I used built-in objects as keys in order to avoid cluttering the example with defining new objects to use as keys, but it's of course possible to use your own objects as keys.
Be careful, however, not to use [] to access elements of a map. Doing myMap[whatever] is valid code so it won't throw an error, but it won't work as expected:
// Don't do this
myMap[Math] = 3;
myMap["[object Math]"] = 4;
console.log(myMap[Math]); //4
console.log(myMap.get(Math)); // 'undefined'
// Do this instead
myMap.set(Math, 3);
myMap.set("[object Math]", 4);
console.log(myMap.get(Math)); //3
To learn more about maps, see Map.

Categories

Resources