Created
January 4, 2016 18:51
-
-
Save freewayz/3a1c71cf737ebce4e4b2 to your computer and use it in GitHub Desktop.
Passing json to object in javascript 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
/* | |
Please feel free to comment and any advice | |
* Created by peter | |
*/ | |
var Person = {} | |
// an empty person object | |
//sample json object, can also be from a server | |
var sampleJson = {'name': 'Peter', 'age': "20"}; | |
//use the javascript Object.assign method to transfer the json from the source[JSON.parse]to the target[Person] | |
// the source is JSON.parse which take a string argument and a function reviver for the key value pair | |
Object.assign(Person, JSON.parse(JSON.stringify(sampleJson), | |
function (k, v) { | |
//we return the key value pair for the json | |
return k, v | |
})) | |
console.log(Person.name) //Peter | |
console.log(Person.age) // age |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment