Object
const obj = {key: value};
Object nested inside of an object
const obj = {
key : value;
key2 : {
innerKey : innerValue;
},
};
Objects in javascript work just like arrays except you can easily access the values inside of an object by calling on the keys. They can also have nested arrays or nested objects inside of them. An example of things that could be an object are as such :
const charEquip = {
hat: "Hero's helmet",
top: "Hero's Plate Armor",
bottoms: "Hero's Plate Legs",
shoes: "Hero's cleaves",
gloves: "Hero's gloves",
weapon: {
primary: "Holy sword",
secondary: "Holy shield",
},
};
Based on the comparison above, there may be a moment where you may want to know what the top-level keys are in an object. If you come across this situation, you can use Object.keys() to find out what the top level keys are :
Object.keys(charEquip);
//=> ["hat", "top", "bottoms", "shoes", "gloves", "weapon"]
By passing the value of the object into object keys, we can ask Javascript to let us know the top-level keys.
To access the inner keys nested inside of an object, you'd have to call on the innerKey as well as the outerKey.
charEquip.weapon.secondary;
//=> "Holy shield"
charEquip[weapon][primary];
//=> "Holy sword"
Compared to arrays where you can call the values inside of an array by using square brackets to call on which part of the array you want to access, object values are called by using square bracket notation or dot notation.
Dot Notation
charEquip.gloves;
//=> "Hero's gloves"
Bracket Notation
charEquip[top];
//=> "Hero's plate armor"
In some situations, you may need to use bracket notation to call on the value of an object as such :
const rickRolled = {
"Never": "never",
"gonna": "gonna",
"give": "let",
"you": "you",
"up": "down",
};
In this example if you were to try to use dot notation to try to access the value of "let", it would give you a syntax error.
rickRolled."give";
// ERROR: Uncaught SyntaxError: Unexpected string
So in this case you would have to use bracket notation.
rickRolled["give"];
//=> "let"
When assigning object keys you must also make sure the keys are specific, otherwise the processor will just log the last value that was logged to the specific key.
const juicy = {
fruit: apple,
fruit: cantaloupe,
fruit: dragonfruit,
}
juicy;
//=> {fruit: dragonfruit}
Top comments (0)