Objects in JS are associative arrays. All objects are copied by link.
Creating objects
We can create an object using the next commands:
const obj = new Object();
const obj = {};
const obj = {
name: 'Andrew',
age: 34
};
Keys are always strings (or symbols); values can be any type. The { ... } form is an object literal — a quick way to create an object with its contents in one step (like array literals [1, 2, 3] or string literals "moose").
Keys without quotes
Quotes around keys are optional when the key is a valid identifier. If the key contains spaces or other special characters, quotes are required:
const cat = {
legs: 3,
name: 'Harmony',
'full name': 'Harmony Philomena Morgan',
color: 'tortoiseshell'
};
Properties
Access
Bracket notation (key as a string) or dot notation (key must be a valid identifier):
cat['name']; // 'Harmony'
cat.name; // 'Harmony'
cat['full name'];
Reading a missing property returns undefined:
const dog = { name: 'Pancake', legs: 4, isAwesome: true };
dog.isBrown; // undefined
Adding
obj.greeting = 'hello';
obj['greeting'] = 'hello';
Deleting
delete obj.name;
Checking
Object.hasOwn(anObject, 'age');
The in operator checks whether a property exists on the object or its prototype chain. The left operand must be a string (or convertible to one); the right operand must be an object:
const point = { x: 1, y: 1 };
'x' in point; // => true
'z' in point; // => false
'toString' in point; // => true — inherited from Object.prototype
const data = [7, 8, 9];
'0' in data; // => true
1 in data; // => true — numbers are converted to strings
3 in data; // => false
Iterating
for (let key in options) {
console.log(`Property ${key} has value: ${options[key]}`);
}
Get property names
Object.keys(options);
Object.keys(options).length; // Number of properties.
Get property values
Object.values(someObj); // We will get an array of values.
Get an array of properties and values
Object.entries(someObj);
Check if two object have the same content:
Object.is(obj1, obj2);
Merge two object with returning a new one:
Object.assign(objectOne, objectTwo);
Object.assign({}, someObject); // When we need to copy an object.
JSON and JS objects
Convert JSON text to a JS value:
JSON.parse(jsonString);
Convert a JS value to a JSON string:
JSON.stringify(jsValue);
Copy objects
const newObj = JSON.parse(JSON.stringify(oldObj));
Methods
let car = {
color: 'red',
open: function() {
console.log('Car was opened!');
}
};
car.open();
Destructuring assignment
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
let options = {
title: "Menu",
width: 100,
height: 200
};
let {title, width, height} = options;
If we want to assign a property to a variable with another name:
let {width: w, height: h, title} = options;
Spreading
Copy properties:
const obj = {
a: 1,
b: 2
};
const newObj = {...ojb};
Associating arrays
Since JS doesn’t have such a type of data, we can utilize objects as associating arrays.
var keyNames = {
32: "space",
37: "left",
38: "up",
39: "right",
40: "down"
};
alert(keyNames[event.keyCode]);
Advanced property creation
We can also create/modify properties using the Object.defineProperty() method:
Object.defineProperty(obj, prop, descriptor);
Descriptior is an object that describes behavior of the property.
Descriptors can have the next properties:
| Property | Description |
|---|---|
| writable | Determines if the property’s value can be changed. If false, the value is read-only. |
| enumerable | Determines if the property appears in loops (e.g., for...in) or methods like Object.keys(). |
| configurable | Determines if the property can be deleted or its descriptor can be modified. |
Object.getOwnPropertyDescriptor(userObj, 'name'); // we will get a descriptor object
Object.defineProperty(userObj, 'name', {
writable: false,
});
Object.defineProperties(userObje, {
name: {writable: true},
age: {writable: false}
});
Andrew Dorokhov