preface

In the actual business development often need to nested call object values, such as obj.a.B.c, normally there is no problem, but if a section in the middle breaks, such as obj object does not have a attribute, then it will cause a direct error. So we usually write obj && obj.a && obj.a.b && obj.a.b.C is very verbose, so we need a get method to simplify this step and improve the error tolerance rate

code

function get(source, path, defaultValue = undefined) {
  // a[3].b -> a.3.b -> [a,3,b]
  const paths = path.replace(/\[(\d+)\]/g."$1").split('. ')
  
  let result = source;
  for (const key of paths) {
    result = Object(result)[key];
    if(result === undefined) {
      returndefaultValue; }}return result;
}
Copy the code

Path can also be an array path, such as obj.a[0].b, so we need the re to convert all [] to. Operator and form an array. result = Object(result)[key]; The reason for wrapping a layer of Object is because null and undefined will report an error, so use Object wrapping.