Repository navigation
JavaScript Objects
JavaScript objects are the same as Ruby hashes. Some languages call these dictionaries.
Objects are collections of name-value pairs. Each name-value pair is property. That is, properties consist of a name with a value. Similarly, Javascript arrays are also pairs of names (or keys) and values, but in arrays the names are ordered numbers (0, 1, 2, etc.). In objects, names are strings, not numbers.
Values can be any datatype, such as strings, numbers, boolean, null, undefined, or symbol. Values can also be a function, in which case the property is called a method. A method is the same as a named function.
Names must be unique. Creating a second property with the same name as another property will overwrite the value associated with the first instance of the name.
A object can be created in several ways:
var myCar = new Object(); //Parentheses!
var myCar = {} //Curly braces!
An object can also be created at the same time as its properties (below).
##Dot Notation
var myCar = new Object(); //Parentheses!
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
or
var myCar = {} //Curly braces!
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
In the first property, make is the name and "Ford" is the value.
##Square Brackets Notation
var myCar = new Object();
myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;
or
var myCar = {
myCar["make"] = "Ford", // Comma, not semi-colon
myCar["model"] = "Mustang",
myCar["year"] = 1969 // No comma
}
or
myCar["make"] ["Ford"];
Note that quotation marks are used around the names. Note also that square brackets are used, which is confusing if you associate square brackets with arrays.
##Object Initializer
var myCar = {
make = "Ford",
model = "Mustang",
year = 1969
}
This is usually the clearest way to create objects.
##Constructor This makes a function that then makes objects by calling the function. The objects have the parameters specified in the function.
##Object.create() This allows you to choose the prototype object for the object you want to create, without having to define a constructor function.
##Objects Inside an Array
var myArray = [
{width: 20, color: red},
{width: 40, color: blue}
]
To access "blue":
myArray[1].color;
or
myArray[1] ['color'];
To access a function in an array:
myArray[1].myMethod
or
myArray[1] [myMethod] // no quotes because myMethod is a function
##Example: Longest String in an Array
This program iterates through an array to find the longest string, then creates an array with a single property consisting of the longest string as the name and the length of the string as the value.
arry = ["truck", "sidewalk", "book"];
var longestElement = arry[0];
var longString = function(array) {
array.forEach(function(ele, index){
if (ele.length > longestElement.length ) { longestElement = ele };
})
};
longString(arry);
var longestString = Object();
longestString[longestElement] = longestElement.length; // works
// longestString.longestElement = longestElement.length; // doesn't work
// longestString["longestElement"] = longestElement.length; // doesn't work
// var longestString = {
// longestElement: longestElement.length
// } // doesn't work'
console.log(longestString);
The goal is to output
Object {sidewalk: 8}
Let's examine each way to add a property to the object, and their output:
var longestString = Object();
longestString["longestElement"] = longestElement.length;
Object {longestElement: 8}
This doesn't work because the variable name is in quotes.
var longestString = Object();
longestString.longestElement = longestElement.length;
Object {longestElement: 8}
Dot notation treats all names as quotes, i.e., automatically adds quotes to the name.
var longestString = {
longestElement: longestElement.length
}
Object {longestElement: 8}
Constructor notation treats all names as quotes, i.e., automatically adds quotes to the name.
var longestString = Object();
longestString[longestElement] = longestElement.length;
Object {sidewalk: 8}
This works. Square bracket notation is superior because it can be used with strings or variables. Square bracket notation explicitly distinguishes strings and variables, i.e., you have to put quotes around strings, and not put quotes around variables. Dot notation and constructor notation assume that all names are strings.
#Accessing Objects
You access the properties of an object with dot-notation:
var carMake = myCar.make;
var carModel = myCar.model;
Square bracket notation is more reliable, for example, you can use a name with a space, e.g., "My name".
var carMake = myCar["make"];
var carModel = myCar['model'];
##Accessing Objects Within Objects
JavaScript Object Notation (JSON) enables accessing properties of an object that is a property of another object.
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
pause_menu.pause_button.someProperty //evaluates to "prop1"
Using dot notation you concatenate, starting with the outermost object on the left and working inward towards the right, each object, ending with the property on the right:
object.object.property
Or you can think of this as a chain of object-property pairs:
object.property.object.property
with the caveat that the middle property.object pair is one item, i.e., the inner object is a property of the outer object.
##Getter Methods
#Adding Properties To an Object
This is easy. You just declare the property:
myCar.make = "Ford"; // Dot notation with a string
myCar["make"] = "Ford"; // Square bracket notation with a string
var myCar = { // Constructor notation with a string
make = "Ford";
}
myCar[make] = "Ford"; // Square bracket with a variable
#Changing Properties in an Object
Change a property value just like adding the property:
myCar["make"] = "Ford";
##Setter Method
#Removing Properties From an Object
Suppose we no longer car about the year of cars in our object:
delete myCar.year;
#Methods to Iterate Objects
for...in iterates over all the enumerable properties of an object. It's similar to forEach() with arrays.
Object.keys(o) returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o.
Object.getOwnPropertyNames(o) This method returns an array containing all own properties' names (enumerable or not) of an object o.
#Methods: Putting Functions in Objects
##This
this enables refering to the object from a method.
#Convert an Array of Arrays Into an Object
var dogs = [
["German Shepherd", "90 lbs.", "Work"],
["Pointer", "40 lbs.", "Hunting"],
["Corgi", "30 lbs.", "Awesomeness"]
];
var myObject = {};
var dogObject = function(outerArray, innerArray) {
outerArray.forEach(function(innerArray) {
myObject[innerArray[0]] = innerArray[1]
});
return myObject;
};
console.log(dogObject(dogs));
// Object {German Shepherd: "90 lbs.", Pointer: "40 lbs.", Corgi: "30 lbs."}
##Convert Arrays in Arrays to Objects in Objects
var dogs = [
["German Shepherd", "90 lbs.", "Work"],
["Pointer", "40 lbs.", "Hunting"],
["Corgi", "30 lbs.", "Awesomeness"]
];
var myObject = {};
var InnerObject = function(size, bredFor) {
this.size = size;
this.bredFor = bredFor;
};
var dogObject = function(outerArray) {
outerArray.forEach(function(innerArray) {
myObject[innerArray[0]] = new InnerObject(innerArray[1], innerArray[2]);
});
return myObject;
};
console.log(dogObject(dogs));