C
C
Coder3212017-01-09 20:34:27
JavaScript
Coder321, 2017-01-09 20:34:27

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' ];

if there is no such key, I need to write a string from the keys array to absentKeys. Can anyone help?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
EVG, 2017-01-09
@Coder321

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 question

Ask a Question

731 491 924 answers to any question