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. :)

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs