Javascript Objects Notes
As javascript objects are used so often in javascript i thought i would write an overview and some notes on how they work, well how they work for me anyway. I guess how they work for me should be similar to how they just work, so should be good.
What is a Javascript Object?
- A javscript object is a collection of named values.
- Objects is an unordered collection of key value pairs.
- Javascript Objects are like an array, but not actually an array.
An example of a Javascript Object
Javascript
const my_object = {
"my_object_1": "value1",
"my_object_2": "value2",
"my_object_3": "value3"
}
Accessing Properties of an Object
Lets take the my_object and access value2 from it.
You can do this with : objectName.property
or like this
objectName["property"]
Javascript
console.log(my_object.my_object_2);
Convert an Object to An Array
You can convert your javascript object into an array with Object.values(objectName);
Javascript
/* an array of the object called my_object_array */
const my_object_array = Object.values(my_object);
console.log(my_object_array);
Loop throught the new array
Usually i forget how to do this, so i thought i would add it here to see if it jogs my memory.
The array is now called my_object_array
This seems to work:
Javascript
/* foreach on the array function */
let out = "";
my_object_array.forEach(do_stuff_function);
function do_stuff_function(value, index, array) {
out += "value: " + value + ", index: " + index + "array: " + array;
}
console.log(out);
Object Methods
You can add things like functions inside objects, which makes them even more useful than arrays.
add code and example...
Constructor
A blue print for creating objects.
Javascript
const my_object = {
"my_object_1": "value1",
"my_object_2": "value2",
"my_object_3": "value3"
}
console.table(my_object);
// console.log the value of my_object.my_object_2
console.log(my_object.my_object_2);
// console.log the value of objectName["property"]
console.log( my_object["my_object_2"] );
// an array of the object called my_object_array
const my_object_array = Object.values(my_object);
console.log(my_object_array);
// foreach on the array function
let out = "";
my_object_array.forEach(do_stuff_function);
function do_stuff_function(value, index, array) {
out += "value: " + value + ", index: " + index + "array: " + array;
}
console.log(out);