Access Elements

Unlike array, elements in an object are not accessed by their position index numbers. Instead, they are identified by the keys.

Accessing object properties in two ways

Dot notation

Property values are accessible using the dot notation: objectName.propertyKey

example:

let cat = {name: 'Sassy', age: 3, 'likes dogs': false }

// access property values:
alert(cat.name);                   // Sassy
alert(cat.age);                    // 3

Dot notation requires the key to be a valid variable identifier, which means it cannot contain spaces or special symbols. The key name is not quoted.

Bracket notation

For property names that contain spaces or special symbols, the dot access doesn’t work. There’s an alternative "square bracket notation" that works with any string:

objectName["propertyKey"]

Note: The string inside the brackets should be properly quoted.

Continue with cat object:

console.log(cat['name']);        // Sassy

console.log(cat['likes dogs']);  // false

Assign value to a key

Similar to arrays, objects are mutable. We can add new key:value pairs or change an existing key's value.

Assignment:

obj.key = value or obj['key'] = value

The assignment adds a new element to the object if the key was not in original object, or replaces the old value with the new value if the key already exists.

We can add another property to cat object using dot notation:

cat.color = 'yellow';

console.log(cat)        // {"name":"Sassy", "age":3, "likes dogs": false, "color":"yellow"}

Or we can change a property using square bracket:

cat['color'] = 'white';

console.log(cat['color']);       // white

For a key string with space we can only use square bracket :

cat['loves fish'] = true;
console.log(cat)      // {"name":"Sassy", "age":3, "likes dogs": false, "color":"white", "loves fish": true}

Delete a property

To delete a property, use

delete obj.key

delete cat.color;

Existence check

To check if a property with the given key exists, use keyword in:

"keyName" in obj

Continue with cat object example:

console.log("name" in cat);       // true (cat.name exists)
console.log("LaLa" in cat);       // false (cat.LaLa doesn't exist)

Please note that on the left side of in there must be a property key name. That’s usually a quoted string.

results matching ""

    No results matching ""