Skip to content

Instantly share code, notes, and snippets.

@seanhess
Last active December 12, 2015 03:28
Show Gist options
  • Save seanhess/4707546 to your computer and use it in GitHub Desktop.
Save seanhess/4707546 to your computer and use it in GitHub Desktop.
//////////////////////////////////////
// LONG WAY //////////////////////////
//////////////////////////////////////
var person = {} // same as "new Object()"
person.name = "sean"
person.friends = []
var friend = {}
friend.name = "isaac"
person.friends.push(friend)
console.log(JSON.stringify(person)) // -> {name:"sean", friends:[{name:"isaac"}]}
////////////////////////////////////
// Object Literals /////////////////
////////////////////////////////////
// Instead you can just write the whole object at once.
// this looks just like JSON (JavaScript Object Notation)
var person = {
name: "sean",
friends: [
{name: "isaac"}
]
}
console.log(JSON.stringify(person)) // same as obove
// You can take the JSON.stringify() output of any object, paste it into your editor as "var something = xxx" and it will work.
var person = {}
// these are the same
person.name = "sean"
person["name"] = "sean"
// useful if you want to do something like this:
// monthId is different in each iteration of the loop, so we can't use person.xxxxx
// lets you make the name of the property be a variable
for (var i = 0; i < 24; i++) {
var monthId = "month" + i
person[monthId] = 0
// or you could set it to a whole object
person[monthId] = {id: monthId, budget: 0}
}
console.log(JSON.stringify(person)) // {name:"sean", month0: 0, month1: 0, month2: 0, ...etc }
// You can loop through the property names of an object if you don't know them.
for (var propertyName in person) {
console.log(propertyName) // "name", "month0", "month1", etc.
}
// You can get an array of property names and loop through them like normal
var propertyNamesArray = Object.keys(person)
propertyNamesArray.forEach(function(propertyName) {
console.log(propertyName) // same as above
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment