Adding and Removing Properties on an Object

by kirupa   |   filed under JavaScript 101

Objects in JavaScript seem fairly simple. They have a name, they use the weird curly braces a lot, and they contain data in the form of property / value pairs:

var superHero = {
  firstName: "Tony",
  lastName: "Stark",
  misc: {
    color: "Red",
    name: "Iron Man",
    affiliate: "Stark Industries"
  }
};

As we have seen in other tutorials, there is more to our friendly JavaScript objects than meets the eye. In this tutorial, we'll look at something that seems pretty straightforward - adding and removing properties from objects. We'll see just how straightforward (or not) this is in a few moments.

Onwards!

Adding Properties

Once you have an object, there are several paths you can take to add additional properties on it. The path we will take is a simple and performant one that uses the array-like bracket notation with your new property name acting as the index.

Let's say we have an object called colors that looks as follows:

var colors = {
  header: "blue",
  footer: "gray",
  content: {
    title: "black",
    body: "darkgray",
    signature: "light blue"
  }
}

We want to add a new property called logo and give it a value of transparent. The way we would add this property is as follows:

colors["logo"] = "transparent";

That's all there is to it. Once you have added this property, you can access it using one of two approaches:

// Approach 1
var logoColor = colors["logo"];

// Approach 2
var logoColor = colors.logo;

It doesn't matter which approach you take. Use whichever makes you (or your team) happy. I tend to favor the second approach with the dot notation, for it is consistent with how we typically access the value of a property. The exception is when you might need to dynamically generate the property name:

var numbers = [0, 1, 2, 3, 4];

for (var i = 0; i < numbers.length; i++) {
  var objValue = myObject["data" + numbers[i]];
  console.log(objValue);
}

In those cases, the first approach is the one that makes the most sense. There aren't any recommended ways (please don't use eval) you can use the second approach with a property name that needs to be created on the fly.

Before we wrap this section up, there is just one more detail about adding properties that we will look at. If you want to add a property to another object that lives within your object (aka a nested object), you combine everything we've seen here to do this. For example, let's say we want to add a property called frame to the object stored by the content property in our colors object:

var colors = {
  header: "blue",
  footer: "gray",
  content: {
    title: "black",
    body: "darkgray",
    signature: "light blue"
  }
}

The way we can do that is as follows:

colors.content["frame"] = "yellow";

If you prefer to use the bracket notation for accesing the content property, you can do this instead:

colors["content"]["frame"] = "yellow";

Before we wrap this up, I mentioned at the beginning that you have several paths that you can take to add properties to an object. We looked at one such path. A more complex path that you can take could involve the Object.defineProperty and Object.defineProperties methods. These methods allow you to set a property and its value, but they allow you to do much more like define getters/setters, specify whether a property can be enumerated, specify whether a property can be customized, and more. It's definitely overkill for what you will want to do 99% of the time, but know this: if overkill is what you want, then these two methods deliver. The MDN documentation does a good job providing examples of how you can use them to add one or many properties to an object.

Removing Properties

If you thought adding properties to an object was fun, removing properties from an object is a bit boring. It is also simpler. Let's continue to work with our colors object:

var colors = {
  header: "blue",
  footer: "gray",
  content: {
    title: "black",
    body: "darkgray",
    signature: "light blue"
  }
}

What we want to do is remove the footer property. We have two ways of doing this depending on whether we want to access the footer property using the bracket notation or whether we want to access it using the dot notation:

delete colors.footer;

// or

delete colors["footer"];

The key to making this all work is the delete keyword. Simply use the delete keyword and follow it up with the property you'd like to remove. That's all there is to it.

Now, this wouldn't be JavaScript if I didn't mention a caveat. This one has to do with performance. If you will be deleting a lot of properties on a frequent basis across a large number of objects, delete is much slower than just setting the value of the property to something like undefined:

colors.footer = undefined;

// or

colors["footer"] = undefined;

The flipside is that setting a property to undefined means the property still exists in memory. You'll need to calculate the tradeoffs (speed vs. memory) in your situation and optimize for the one that makes the most sense for you.

Conclusion

Anyway, there is actually a whole lot more we can talk about here. For example, ES6 introduces some crazy new ways of dealing with properties inside an object, and some of them do change how we can add and remove properties as well. Like with any good story, the trick is knowing when to stop. Clearly, I have much to learn.

If you have a question about this or any other topic, the easiest thing is to comment below or drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )

WHAT'S ON YOUR MIND

HOT FORUM TOPICS

Serving you freshly baked content since 1998!

Killer hosting by (mt) mediatemple

Facebook Twitter Youtube Pinterest Instagram Github
BACK TO TOP
new books - yay!!!