Object flattening in javascript?

why hasOwnProperty is used in recursive calls?

var obj = {
    name: 'brinth',
    age:21,
    address:{
    	local:'no 7 ,2nd main road',
    	permanent:'no 4,3rd main road tms'
    },
    role:'student'
}

var flatten = function(ob) {
	var toReturn = {};
	
	for (var i in ob) {
		if (!ob.hasOwnProperty(i)) continue;
		
		if ((typeof ob[i]) == 'object') {
			var flatObject = flatten(ob[i]);
			for (var x in flatObject) {
				if (!flatObject.hasOwnProperty(x)) continue;
				
				toReturn[i + '.' + x] = flatObject[x];
			}
		} else {
			toReturn[i] = ob[i];
		}

for…in doesn’t just get object properties, and also includes any from parent objects via the prototype chain.

It’s checking if the property belongs to that actual object.

1 Like

Oh ok got it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.