JavaScript Data Structuring

An ES6 feature that allows you to unpack array or an object and assign each value to a variable.

// Simple array
const arr = [2, 3, 4];
const [x, y, z] = arr; // creates 3 variables: x=2, y=3, z=4.

const [a, ,b] = arr; // misses out middle array value (a=2, b=4)

// switching variables
let first = "starter";let second = "main";
[first, second] = [second, first]; // first = main, second = starter

// nested arrays
const nested = [2, 4, [5, 6]];
const [, ,[j, k]] = nested; // j = 5, k = 6

// default values
const [p=1, q=1, r=1] = [8, 9]; // p=8, q=9, r=1

Destructuring Objects

Use curly braces to destructure objects. You use the property names as variable names.

const {propertyName1, propertyName2} = myObject; // desctructuring using property names.

const {propertyName1: myName, propertyName2: myName2} = myObject // destructuring with custom variable names

// setting default values (in case the property doesn't exist)
const {menu = [], starters: starterMenu = []} = myObject;

Mutating Objects

Surround the code with brackets to create a code block.

let a = 111;
let b = 999;
const obj = { a: 23, b: 7. c: 14 };
({ a,b } = obj); // not allowed to use const or let as variables are already declared - add brackets to prevent error and create a code block.

Nested objects

const { fri: { open: o, close } } = openingHours;
// fri is the property name of the first object which has open and close nested object. This syntax will create new variables "o" and "close" which will be Friday opening and closing hours

Destructuring objects with functions/methods

you can destructure objects passed in functions using curly brackets within the function parameters. You can also set default values as before.

restaurant = {
 name: "My Restaurant";
 // this method will destructure a passed object into four variables (using property names)
 orderDelivery: function ({starterIndex = 0, mainIndex = 1, time, address}) {
   console.log("delivery address:" + address);
 }
}

restaurant.orderDelivery({
 // create an object:
 time: '22:30',
 address: '29 This Street, This Town',
 mainIndex: 1,
 starterIndex: 2
});

Spread Operator

Scenario: Create a new array that has two values and then all the values of another array

const = oldArray = [3, 4, 5];
const = newArray = [1, 2, ...oldArray]; // newArray equals 1,2,3,4,5

Spread operator descructures a literal array but does not create new variables for each value.

Can be used to create shallow copies of arrays or merging arrays:

const copiedArray = [...originalArray]; // copy array
const firstAndSecondArray = [...firstArray, ...secondArray]; // merged arrays

Can also be used on any iterables (ie can break down a strings, maps, sets).

const str = 'word';
const letters = [...str]; Creates an array "w","o","r","d"

The spread operator can also be used as the parameter in a function to deconstruct an array and then pass the individual arguments.

Can be used to copy objects too as before.

Rest Pattern

Rest pattern does the opposite of the spread operator. Used to collect multiple elements and condense them into an array.

Uses the spread operator but on the left side of the equals operator

const [a, b, ...others] = [1,2,3,4,5]; // a = 1, b = 2, others = [3,4,5]

REST ELEMENT MUST BE THE LAST ELEMENT OF THE ARRAY. THERE CAN BE ONLY ONE.

Can be used in objects to pick properties out of existing objects.

const { sat, ...weekdays } = restuarant.openingHours; // creates an object of sat and an object of weekdays which includes all the properties of the remaining days less saturday.
Use case:

Can be used in functions when any number of arguments can be passed:

// rest parameter
const add = function (...numbers) {
  let sum = 0;
  for( let i = 0; i<numbers.length; i++) sum += numbers[i];
  return sum;
}

// can pass any number of arguments
add(2,3);
add(1,2,5,6);
const x = [23,5,7];
add(...x); // spread parameter to pass each value of the array.

The above example allows you to pass either an array or multiple single arguments through the function parameters.

Additional use in method

restaurant = {
 orderPizza = function(mainIngredient, ...otherIngredients){
  // will create a variable of first value of the arguement, and then an array of all the other arguments.
 }
};

The spread and the rest look exactly the same but work in opposite ways depending on where they are used.

Spread: Used where we would otherwise write values seperated by a comma

Rest: Used where we would otherwise write variable names separated by commas.

Leave a Reply

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