Last active
September 29, 2021 07:04
-
-
Save bencharb/9375912 to your computer and use it in GitHub Desktop.
JSON map to JSON object
This file contains 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
/* | |
Credit: Tomalak on Stack Overflow | |
http://stackoverflow.com/a/11153997 | |
Why? | |
Easier to pull data when the mapping is unknown or arbitrary. | |
Example: | |
the function nestedMapping() turns your data structure: | |
{ | |
"Level 1a": "Hi", | |
"Level 1b": { | |
"Level 2a": "Hello", | |
"Level 2b": { | |
"Level 3": "Bye" | |
} | |
} | |
} | |
into: | |
[ | |
{ | |
"key": "Level 1a", | |
"type": "simple", | |
"value": "Hi" | |
}, | |
{ | |
"key": "Level 1b", | |
"type": "array", | |
"value": [ | |
{ | |
"key": "Level 2a", | |
"type": "simple", | |
"value": "Hello" | |
}, | |
{ | |
"key": "Level 2b", | |
"type": "array", | |
"value": [ | |
{ | |
"key": "Level 3", | |
"type": "simple", | |
"value": "Bye" | |
} | |
] | |
} | |
] | |
} | |
] | |
*/ | |
var ListModel = function(jsonData) { | |
var self = this; | |
self.master = []; | |
function nestedMapping(data, level) { | |
var key, value, type; | |
for (key in data) { | |
if (data.hasOwnProperty(key)) { | |
if (data[key] instanceof Object) { | |
type = "array"; | |
value = []; | |
nestedMapping(data[key], value); | |
} else { | |
type = "simple"; | |
value = data[key]; | |
} | |
level.push({key: key, type: type, value: value}); | |
} | |
} | |
} | |
nestedMapping(jsonData, self.master); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment