Validate property in Object Javascript

var validateProperty = function(obj, key) {
 return key.split(“.”).reduce(function(prop, index) {
 return (typeof prop == “undefined” || prop === null) ? prop : prop[index];
 }, obj);
};

var miObj = {
 completeName: {
 name: “isaac”,
 lastName: “salgado”
 }
};

var property = “completeName.lastName”;
console.log(validateProperty(miObj, property));

//return “salgado”

var property = “completeName.lastName2”;
console.log(validateProperty(miObj, property));

//return “undefined”


Regards

Isaac

Like what you read? Give Isaac Salgado a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.