Answer the question
In order to leave comments, you need to log in
Checking an object for keys?
I have an object that needs to be checked for presence and there is a array of keys that need to be checked, an array like this:
let absentKeys = [];
let keys = [ 'test', 'user.name', 'article.author.name' ];
Answer the question
In order to leave comments, you need to log in
function isHasPropertyChain(obj, propertyChain){
if(!(obj instanceof Object)) throw new TypeError("obj должен быть объектом");
if((!(propertyChain instanceof Array)) && (!(typeof(propertyChain) === 'string'))) throw new TypeError("propertyChain должен строкой или массивом");
var properties = (propertyChain instanceof Array)
? propertyChain
: propertyChain.split('.');
if (properties.length == 0) return false;
var testedProp = properties[0];
var res = (testedProp in obj);
if(res){
if((properties.length > 1)){
return (obj[testedProp] instanceof Object) && isHasPropertyChain(obj[testedProp], properties.splice(1));
}
}
return res;
}
function predicator(v){
return !isHasPropertyChain(this, v);
}
var obj = {/* тестируемый объект */};
absentKeys = keys.filter(predicator, obj);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question