Skip to content

Instantly share code, notes, and snippets.

@freewayz
Created January 4, 2016 18:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freewayz/3a1c71cf737ebce4e4b2 to your computer and use it in GitHub Desktop.
Save freewayz/3a1c71cf737ebce4e4b2 to your computer and use it in GitHub Desktop.
Passing json to object in javascript object
/*
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