DEV Community

loading...

Discussion on: PHP 8 features I wish also existed in JavaScript

Collapse
groundhogs profile image
Ground Hogs

You could always use something like this for the last one (fairly sure I did something similar in PHP before this was an option):

function get(obj, path=[], fallback=null, separator="."){
  if(path.constructor === String){
    path = path.split(separator);
  }

  return path.reduce(
    (r, k) => r[k] || fallback,
    obj
  );
}
/** 
# Examples

const convolutedObject = {a:1,b:{a:2,b:{a:3,b:{a:4,b:5}}}};
get(convolutedObject, ["b","c"], "wrong"); // "wrong"
get(convolutedObject, "b.b.b.a"); // 4
*/
Enter fullscreen mode Exit fullscreen mode