Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[JavaScript] Objects

These are my notes while doing the course JavaScript Algorithms and Data Structures on https://www.freecodecamp.org. I highly recommend it if you prefer to try things directly rather than watching videos.


Objects are similar to arrays, except that instead of using indexes to access and modify their data, you access the data in objects through what are called properties. Objects are useful for storing data in a structured way, and can represent real world objects.

var myDog = {
    "name": "Dog",
    "legs": 4,
    "tails": 1,
    "friends": ["Max", "Matilda"]
};

Note: If your object has any non-string properties, JavaScript will automatically typecast them as strings.


There are two ways to access the properties of an object: dot notation (.) and bracket notation ([]), similar to an array.

var myObj = {
  prop1: "val1",
  prop2: "val2"
};

var prop1Dot = myObj.prop1; // val1
var prop2Dot = myObj.prop2; // val2

var prop1Bracket = myObj["prop1"]; // val1
var prop2Bracket = myObj["prop2"]; // val2

Append / Delete Properties with dot or bracket notation.

var myObj = {
  prop1: "val1",
  prop2: "val2"
};

ourDog.prop3 = "val3";
ourDog["prop4"] = "val4";

delete myObj.prop3;
delete myObj["prop4"];

Note: Bracket notation is required if your property has a space in it or if you want to use a variable to name the property.


Check if the property of a given object exists or not using the hasOwnProperty() method or the in keyword.

var myObj = {
  prop1: "val1",
  prop2: "val2"
};

myObj.hasOwnProperty("prop1"); // true
myObj.hasOwnProperty("prop3"); // false

'prob1' in myObj; // true
'prob3' in myObj; // false

JSON – an array of objects https://www.json.org/json-en.html

var myObj = [{
  prop1: "val1",
  prop2: "val2"
},
{
  prop1: "val1",
  prop2: "val2"
}];

console.log(JSON.stringify(myObj));

Generate an Array of All Object Keys

Using the Object.keys() method and passing in an object as the argument will return an array with strings representing each property in the object.

let users = {
  Max: {
    age: 27
  },
  Mira: {
    age: 32
  },
  Rich: {
    age: 48
  }
};

function getArrayOfUsers(obj) {
  return Object.keys(obj);
}

getArrayOfUsers(users); // [ 'Max', 'Mira', 'Rich' ]

Note: Also have look at ES6 which includes new object syntax for constructors, getters and setters etc.

Leave a Reply

Your email address will not be published. Required fields are marked *