Tuesday, September 8, 2020

safely unpacking nested key/values in javascript/ECMAscript - the mess of the null propagation operator

 So if you have an object like 

const foo = {
  bar: {
    val: 'got this!'  
  },
  apple:{
    banana:{
      cherry: 'fruit'
    }
  }
};

and you want to safely get foo.bar.val or check on foo.baz.val without getting errors... there's a good syntax for it based on question marks - but isn't yet part of the the standard: foo?.bar?.val or foo?.baz?.val - it's scary, because it seems to work in some browsers, but isn't considered standard.

I made up a code pen that says something like this function might be an ok substitute, if less clean:

function getNested(obj,...keys){
  keys.forEach((key)=>{
    if(obj === undefined || obj === null) {
      return;
    }
      obj = obj[key]; 
  });
  return obj;
}

Then you can call getNested(foo,'baz','val')

No comments:

Post a Comment