DEV Community

Discussion on: JavaScript techniques you wish you knew involving objects

Collapse
 
functional_js profile image
Functional Javascript • Edited

Great comprehensive writeup Jack.

A good trick for accessing data in deeply nested structures is using the power of JavaScript's lambdas.

You can think of passing functions around as passing scope around.

/*
@func
return the value at the end of the obj or arr chain
- if any of the vals or arr accessors along the chain don't exist
- then return null

@param {() => *} fn - the lambda wrapping the nested call, via dot notation
@return {*|null} - the val in the key-val pair at the end of the dot notation chain
*/
export const getVal = fn => {
  try {
    return fn();
  } catch {
    return null;
  }
};

//@tests
const obj = { manuf: "Acme" };
const val = getVal(() => obj.k1.k2.k3.arrOfObjs[0].k5.k6.trim().toLowerCase().length);
console.log(val);
/*
note:
this example returns null since this path doesn't exist in the obj
*/