DEV Community

Collins Mutai
Collins Mutai

Posted on

JavaScript ES6 Object & Array Destructuring.

Arrays is a great way to store complex data in programming. But how do we access the stored data? This can be easily achieved using destructuring.
Let's say we have an array with two objects.

const animals = [{ name: "cat", sound: "meow",
{ name: "dog", sound: "woof" }];

We can access the two objects properties like so.

const [cat, dog] = animals;

Then we use curly braces to get hold of the cat object.

const { name, sound } = cat;

console.log(cat); // Object {name: "cat", sound: "meow"}
console.log(name); // "cat"
console.log(sound); // "meow"

Change property name of an object

To change the property name, we assign the new name like so.

const { name: catName, sound:catSound } = cat;
console.log(catSound); //"meow"

Assign default values to an object

To change the default values, we assign the values like so.

const { name="fluffy", sound="purr" } = cat;
console.log(name); //"fluffy"

Destructure nested objects

Sometimes we have an object inside an object, which we call nested objects

const animals = [{
name: "cat",
sound: "meow",
feeding: {
water: 1,
food: 3
}
},
{ name: "dog", sound: "woof" }];

To destructure nested objects, we use a set of curly braces like so.

const { name, sound, feeding:{water,food}} = cat;
console.log(food); //3

Thanks for checking it out. :)

Top comments (0)