Working with objects in JavaScript

Thursday, Jul 30, 2020
JavaScript

Create objects from variables

const year = 2019;
const type = "truck";
const isNew = true;

const vehicles = {year, type, isNew}
console.log(vehicles);
// { year: 2019, type: 'truck', isNew: true }

Note: This can also be used for better console logging. By simply using {varName} to log a variable, it will be logged in key: value which is nice.

Getting keys and values of objects

Returns an array:

console.log(Object.keys(vehicles));
// [ 'year', 'type', 'isNew' ]

console.log(Object.values(vehicles));
// [ 2019, 'truck', true ]

Check for a key

"year" in vehicles
// true

vehicles["year"] !== undefined
// true

Deleting a key

const fruits = {apples: 12, oranges: 13, kiwi: 5};
delete fruits["apples"];

Merging objects

{...obj1, ...obj2} will merge the two objects. If common keys exist in the two objects, second object will overwrite the first values for those keys.

const updateVehicles = {...vehicles, ...{isNew: false, color: "red"}}
console.log(updateVehicles);
// { year: 2019, type: 'truck', isNew: false, color: 'red' }

Getting values using key strings

Instead of dot notation, key strings can be used. This can be useful when keys are obtained programatically and are stored in variables.

const keys = Object.keys(updateVehicles);
console.log(updateVehicles[keys[3]]);
// red

Destructuring an object

Objects can be destructured using {key1, key2} = objName notation. This will result in new variables with values from the object on the right. Default values can be provided (as shown in the example below). The variable would take that value if the corresponding key does not exist in the object.

const {color, transmission = "auto"} = updateVehicles;
console.log(color, transmission);
// red auto