Note that there are some explanatory texts on larger screens.

plurals
  1. POParse JSON String into a Particular Object Prototype in JavaScript
    primarykey
    data
    text
    <p>I know how to parse a JSON String and turn it into a JavaScript Object. You can use <code>JSON.parse()</code> in modern browsers (and IE9+).</p> <p>That's great, but how can I take that JavaScript Object and turn it into a <em>particular</em> JavaScript Object (i.e. with a certain prototype)?</p> <p>For example, suppose you have:</p> <pre><code>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 </code></pre> <p>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'.</p> <p><strong>UPDATE</strong> After doing some research, I thought of this...</p> <pre><code>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); </code></pre> <p>Will that work?</p> <p><strong>UPDATE May, 2017</strong>: The "modern" way of doing this, is via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign" rel="noreferrer"><code>Object.assign</code></a>, but this function is not available in IE 11 or older Android browsers.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload