DEV Community

John Josef
John Josef

Posted on

Keys to the object

Object

const obj = {key: value};
Enter fullscreen mode Exit fullscreen mode

Object nested inside of an object

const obj = {
key : value;
key2 : {
innerKey : innerValue;
    },
};
Enter fullscreen mode Exit fullscreen mode

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",
   },
};  
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode
charEquip[weapon][primary];
//=> "Holy sword"
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Bracket Notation

charEquip[top];
//=> "Hero's plate armor"
Enter fullscreen mode Exit fullscreen mode

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",
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

So in this case you would have to use bracket notation.

rickRolled["give"];
//=> "let"
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)