// Tutorial //

Dealing With Objects in JavaScript With Object.assign, Object.keys and hasOwnProperty

Published on September 29, 2017
Default avatar
By Alligator.io
Developer and author at DigitalOcean.
Dealing With Objects in JavaScript With Object.assign, Object.keys and hasOwnProperty

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

This post is a sort of grab bag to help you explore a few very useful methods to help you manage your objects in JavaScript. We’ll explore Object.keys, Object.prototype.hasOwnProperty and the newer Object.assign.

hasOwnProperty

hasOwnProperty is a method available on object instances that allows to check if an object has a property directly on its instance. Here’s a simple example that should illustrate this very clearly:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

console.log('clown' in myObj); // true
console.log('valueOf' in myObj); // true

console.log(myObj.hasOwnProperty('clown')); // true
console.log(myObj.hasOwnProperty('valueOf')); // false

Object.keys

The Object.keys static method returns an array with the property keys on an object:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

console.log(Object.keys(myObj));

// ["clown", "police", "santa", "farmer"]

Object.keys can be really useful in allowing to use a for…of loop over an object:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

for (let k of Object.keys(myObj)) {
  console.log(`Hey ${ myObj[k] }!`);
}

// "Hey 🤡!"
// "Hey 👮!"
// "Hey 🎅!"
// "Hey 👩‍🌾!"

Note that in the array returned from Object.keys, the keys won’t necessarily be in order.

Object.assign

ES2015 (ES6) brings us a new static method on the Object constructor: Object.assign. This new method allows to easily copy values from one object to another. Notice in the following example how we use an empty object literal and copy over the properties from myObj to create a new object (myObj3) that’s a copy of myObj:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

const myObj2 = myObj;

const myObj3 = Object.assign({}, myObj);

console.log(Object.is(myObj, myObj2)); // true

console.log(Object.is(myObj, myObj3)); // false

console.log(myObj3);

// Object {
//   clown: "🤡",
//   farmer: "👩‍🌾",
//   police: "👮",
//   santa: "🎅"
// }

In case you’re wondering, Object.is is a method used to check if two objects are the same.

Note that only an object’s enumerable properties will be copied over with Object.assign.

The first argument is the source object, and the subsequent arguments are source objects. You can pass-in multiple source objects, and duplicate properties in sources passed last will win:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

const myObj2 = Object.assign({}, myObj, {
  santa: '🎄',
  teacher: '👩‍🏫'
});

console.log(myObj2);

// Object {
//   clown: "🤡",
//   farmer: "👩‍🌾",
//   police: "👮",
//   santa: "🎄",
//   teacher: "👩‍🏫"
// }

Today with the likes of Redux for state management, Object.assign becomes really useful to create completely new objects from existing ones, allowing you to copy and expand objects in an immutable manner.

Bonus: Object.freeze

Use Object.freeze to shallowly freeze an object to prevent its properties from being changed. Note in this following example how, after using Object.free on an object, we can’t change a property, add a new one or delete one:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

myObj.clown = 'scary';
myObj.astronaut = '👨‍🚀';

Object.freeze(myObj);

myObj.clown = 'really scary';
myObj.student = '👩‍🎓';
delete myObj.santa;

console.log(myObj);

// Object {
//   clown: "scary",
//   farmer: "👩‍🌾",
//   police: "👮",
//   santa: "🎅",
//   astronaut: "👨‍🚀"
// }

There’s also another useful method, Object.isFrozen, to know if an object has been frozen:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾'
}

console.log(Object.isFrozen(myObj)); // false

Object.freeze(myObj);

console.log(Object.isFrozen(myObj)); // true

Note that nested objects won’t automatically be frozen by Object.freeze. In the following example, the nested animals object can still have its properties changed or deleted even after the containing object has been frozen:

const myObj = {
  clown: '🤡',
  police: '👮',
  santa: '🎅',
  farmer: '👩‍🌾',
  animals: {
    cow: '🐄',
    rabbit: '🐇'
  }
}

Object.freeze(myObj);

delete myObj.animals.rabbit;
myObj.animals.cow = 'moo!';

console.log(myObj);

// Object {
//   clown: "🤡",
//   farmer: "👩‍🌾",
//   police: "👮",
//   santa: "🎅",
//   animals: {
//     cow: 'moo!'
//   }
// }

In order to deep-freeze an object, we would have to instead recursively freeze any object property that happens to also be an object. Here’s a good utility to make deep freeze a breeze.

👨‍🔬 P.S.: You may also be interested in learning about the new Object.values & Object.entries methods.


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?
Leave a comment

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!