Skip to content

Instantly share code, notes, and snippets.

@GavinRay97
Last active December 25, 2017 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GavinRay97/804e04a04aec1aae4e7f91031c79c070 to your computer and use it in GitHub Desktop.
Save GavinRay97/804e04a04aec1aae4e7f91031c79c070 to your computer and use it in GitHub Desktop.
Working with Complex Objects via ES6 Object Destructuring/Pattern Matching
var myObject = {
name: 'myObject',
number: 9001,
nestedObject: {
nestedName: 'nestedName',
nestedBasicArray: [1,2,3],
nestedObjectArray: [{firstThing: 11, secondThing: 12}, {firstThing: 21, secondThing: 22}, {firstThing: 31, secondThing: 32}]
}
}
var {
name,
number,
nestedObject: {
nestedName,
nestedBasicArray: [a, b, c],
nestedObjectArray: [...d]
}
} = myObject
// These values have the same key name in our object, so we declare and call them directly
console.log(`Name is ${name}`)
console.log(`Name is ${number}`)
console.log(`Nested Name is ${nestedName}`)
// Here we use some basic pattern matching
console.log(`a is ${a}`)
console.log(`b is ${b}`)
console.log(`c is ${c}`)
// We use the object spread '...' operator to deconstruct this array of objects
console.log('d is:')
console.log(d);
// Let's use an example function to dig a little deeper
d.forEach(({firstThing, secondThing}) => {
console.log(`firstThing is ${firstThing}`);
console.log(`secondThing is ${secondThing}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment