When you’re working with objects you often need to know if a properties already exists in an object, for doing that there is 2 solutions that are already working fairly well. But when you look for undefined properties on multiple levels, it rapidly becomes a mess.

An example

if(typeof object.props1.props2 == "undefined"){
// do stuff

If props1 is undefined, unfortunately your browser is going to throw you that object.props1 is undefined.

Rewinding a bit

First, let’s take a look at your options if your only working on one level, let’s say you want to know if prop1 exists in an object

First solution:

if(object.hasOwnProperty("props1") ){
 // Do stuff

It is pretty self exploratory, it looks in the object if it’s got the property props1, however it is not going to look in the prototype. That could be a good thing or a bad thing, depending on what you are looking for.

Second solution:

if(props1 in object){
// do stuff

That is also a nice solution, I suppose you have guessed the difference, if/in will look down in the prototype for the property.

A small warning, using if/in on array’s is not a good idea, in that case it will look in the prototype and find, for example, toString. If you augment the array prototype it will iterate on these too.

What about an unknown level deep down an object.

Unfortunately there is nothing native to do that. In php, you could do isset() on anything and it would work, we are not that lucky.

Still, there is a way to do it, the idea is to iterate in the object level until we hit undefined.

		// we pass the object and the props as an array ["props1", "props2"]
		function isset(object, props){
			// we will use the dump variable to iterate in the object
			var dump,
				propsLength = props.length -1;
			// loop in the properties 
				// first prop?
				if(x == 0) {
					// add the object to dump (object.props1)
					dump = object[props[x]];
				// Undefined? return false
				if(typeof dump == "undefined" || typeof dump[props[x]] == "undefined"){
					return false;
					// move in the object level 
					// object.props1.props2
					// object.props1.props2.props3
					dump = dump[props[x]];
					// return true, of even return the object back
					if(x == propsLength) return true;

You would use it that way:

if( isset(object, ["props1", "props2", "props3"]) ){
// do stuff


(console.log needed)View demo

That’s it

I’m sure it can be a bit optimized, but you know, it does its job pretty well, hope it helps you guys too!

5 thoughts on “Managing undefined properties on multiple level in objects in javascript

Comments are closed.