DEV Community

Cover image for ⚡ object destructuring in JS: renaming properties⚡
Benjamin Mock
Benjamin Mock

Posted on

⚡ object destructuring in JS: renaming properties⚡

Want to get better at Web Development 🚀🚀🚀? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/


In the last part of this series, we learned how to destructure objects and access object properties. This time we will see, how to rename properties. Let's do a small recap:

const pastry = {
  name: "waffle",
  sweetness: 80,
  ingredients: ["flour", "butter", "eggs"],
  origin: {
    country: "Greece",
    name: "obelios",
    year: 1200,
  }
};

we can access properties via the dot notation

const name = pastry.name;
console.log(name); // "waffle"

or via destructuring

const { name } = pastry;
console.log(name); // "waffle"

But if we want to choose a name for our variable, we seem to be a bit limited with destructuring. For the dot notation it's easy:

const pastryName = pastry.name;
console.log(pastryName); // waffle

But also while restructuring objects it's possible to freely name the variables via a colon.

const { name: pastryName } = pastry;
console.log(pastryName); // waffle

As you can see there are two name properties: one in the top-level (waffle) and one in the nested origin object (obelios). When we want to destructure both of them, we have to rename at least one of them. Let's do this with the one in the nested origin object.

const { name, origin: { name: originName } } = pastry;
console.log(name); // waffle
console.log(originName); // obelios

Want to get better at Web Development?
🚀🚀🚀subscribe to the Tutorial Tuesday ✉️newsletter

Top comments (0)