Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class Serializable {
  2.  
  3.   public static createInstanceFromJson<T>(objType: { new(): T; }, json: any) {
  4.     const newObj = new objType();
  5.     const relationships = objType["relationships"] || {};
  6.  
  7.     for (const prop in json) {
  8.       if (json.hasOwnProperty(prop)) {
  9.         if (newObj[prop] == null) {
  10.           if (relationships[prop] == null) {
  11.             newObj[prop] = json[prop];
  12.           }
  13.           else {
  14.  
  15.             if (json[prop] instanceof Array) {
  16.               newObj[prop] = [];//init array
  17.               for (let i = 0; i < json[prop].length; i++) {
  18.                 let val =  Serializable.createInstanceFromJson(relationships[prop], json[prop][i]);
  19.                 newObj[prop].push(val);
  20.               }
  21.             } else {
  22.               newObj[prop] = Serializable.createInstanceFromJson(relationships[prop], json[prop]);
  23.             }
  24.           }
  25.         }
  26.         else {
  27.           console.warn(`Property ${prop} not set because it already existed on the object.`);
  28.         }
  29.       }
  30.     }
  31.  
  32.     return newObj;
  33.   }
  34.  
  35.  
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement