xuyuan923 / DailyJS

JavaScript每日一练
0 stars 0 forks source link

2015.1.23 Array.prototype.reduce #2

Open xuyuan923 opened 9 years ago

xuyuan923 commented 9 years ago

现在你有一个复杂的多重嵌套的对象,但是你莫名蛋疼,突然就不想用if obj.property == null这个方法。于是乎打算,在Object的原型上创建一个方法(prototype method),传递一个路径,返回undefined 或 值(value)

Object.prototype.hash = function(path){

}

var obj = {
  person: {
    name: 'joe',
    history: {
      hometown: 'bratislava',
      bio: {
        funFact: 'I like fishing.'
      }
    }
  }
};

obj.hash('person.name'); // 'joe'
obj.hash('person.history.bio'); // { funFact: 'I like fishing.' }
obj.hash('person.history.homeStreet'); // undefined
obj.hash('person.animal.pet.needNoseAntEater'); // undefined
xuyuan923 commented 9 years ago
Object.prototype.hash = function(name) {
    try {
        return new Function("a", "return a." + name + ";")(this);
    } catch(e) {
        return undefined;
    }
};
xuyuan923 commented 9 years ago
Object.prototype.hash = function(path) {
  return path.split('.').reduce(function(obj, key){ return obj && obj[key]; }, this);
};