Last active
September 20, 2016 07:26
-
-
Save johnoscott/e399f4da2c7718fbbc174305d2f556e7 to your computer and use it in GitHub Desktop.
Use lodash to inflate a flattened JSON object expressed as path, value, type triplets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export class FlatJSON { | |
| /* @ngInject */ | |
| constructor() { | |
| console.log("FlatJSON Service Init") | |
| console.debug("FlatJSON running tests...") | |
| this.test(); | |
| } | |
| toJSON(keys) { | |
| var o = keys.reduce( (a,pair) => { | |
| switch (pair.type) { | |
| case 'string' : { pair.value = pair.value.toString(); break;} | |
| case 'number' : { pair.value = parseInt(pair.value); break;} | |
| case 'null' : { pair.value = null; break;} | |
| case 'boolean' : { pair.value = (pair.value=='true'); break;} | |
| } | |
| _.set(a,pair.key, pair.value); | |
| return a | |
| },{}); | |
| return o; | |
| } | |
| test() { | |
| let dump = (name, obj) => console.log(name, "->", JSON.stringify(obj,null,2)); | |
| let tests = [ | |
| [], | |
| [ { key:"order.id",value:"12345678",type:"string" }, | |
| { key:"order.createdDate",value:"2016-07-01",type:"string" }, | |
| { key:"order.jobs[0].id",value:"123",type:"string" }, | |
| { key:"order.jobs[0].submittedDate",value:"2016-07-01",type:"string" }, | |
| { key:"order.jobs[0].product.name",value:"Cool Blue 2016",type:"string" }, | |
| { key:"order.jobs[0].product.brand",value:"Rayban",type:"string" }, | |
| { key:"order.jobs[0].product.quantity",value:"2",type:"number" }, | |
| { key:"order.jobs[0].product.inStock",value:"true",type:"boolean" }, | |
| { key:"order.jobs[1].product.name",value:"Cool Blue 2016",type:"string" }, | |
| { key:"order.jobs[1].product.brand",value:"Rayban",type:"string" }, | |
| { key:"order.jobs[1].product.quantity",value:"7",type:"number" }, | |
| { key:"order.jobs[1].product.inStock",value:"false",type:"boolean" }, | |
| ] | |
| ] | |
| tests.forEach((keys,i) => dump(i, this.toJSON(keys))); | |
| // produces this result | |
| let result = { | |
| "order": { | |
| "id": "12345678", | |
| "createdDate": "2016-07-01", | |
| "jobs": [ | |
| { | |
| "id": "123", | |
| "submittedDate": "2016-07-01", | |
| "product": { | |
| "name": "Cool Blue 2016", | |
| "brand": "Rayban", | |
| "quantity": 2, | |
| "inStock": true | |
| } | |
| }, | |
| { | |
| "product": { | |
| "name": "Cool Blue 2016", | |
| "brand": "Rayban", | |
| "quantity": 7, | |
| "inStock": false | |
| } | |
| } | |
| ] | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment