What's an Object?
Objects are JavaScripts most fundamental datatype.
An object in javascript is a collection of unordered key-value pairs, and those values can be other primitve types or other objects.
// ...
{
"type": "articles",
"id": "1",
"attributes": {
"title": "Rails is Omakase"
},
"relationships": {
"author": {
"links": {
"self": "/articles/1/relationships/author",
"related": "/articles/1/author"
},
"data": { "type": "people", "id": "9" }
}
}
}
// ...
//Javascript object example
Creating Objects
Objects can be created with:
- Object literal
let Obj = { "firstname" : "John", "lastname": "Despa", "age": 30 }
- new Keyword
let newObj = new Object(); //creates an empty object
- Object.create() function
let newObj = Object.create({a: 1, b: 2});
This method uses it's first argument as the prototype of the newly created object.
Querying and Setting properties
let Obj = {
color: "red",
value: "#f00"
}
//accessing a value
// Obj.color => "red"
// Obj["value"] => "#f00"
// Obj.color = "blue" => change a value or create new key-value pair if doesn't exist
When using square bracket notation the expression should be a string or value that can be converted to a string
Deleting properties
Properties can be deleted using the delete operator.
delete Obj.color
or
delete Obj["color"]
// delete the color property
The delete expression will evaluate to true if the delete was successful or if the property didn't exist or even when used with a value that is not a property in object.