Skip to content

Instantly share code, notes, and snippets.

@axetroy
Last active April 25, 2017 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/d295f16acc5bc63ff9caac4c2a00e438 to your computer and use it in GitHub Desktop.
Save axetroy/d295f16acc5bc63ff9caac4c2a00e438 to your computer and use it in GitHub Desktop.
解析多层属性,类似angularJS的$parse服务
function parse(properties) {
const agm = properties.split('.');
return function(target, undefined) {
let result = null;
(function parseTarget(target, agm) {
if (target === void 0) {
console.error(
'Uncaught TypeError: Cannot read property ' + agm[0] + ' of undefined'
);
result = target;
return result;
}
if (agm.length <= 1) {
result = target[agm[0]];
return result;
}
target = target[agm[0]];
agm.shift();
parseTarget(target, agm);
})(target, agm);
return result;
};
}
@axetroy
Copy link
Author

axetroy commented Apr 24, 2017

const o = {
  a: {
    b: {
      c: 233
    }
  }
};

console.log(parse('a.b.c')(o)); // 233

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment