Safely get a nested value inside an object

Today, I will share how could you safely get a nested value rather using hacks like this
const nestedVal = (
  obj &&
  obj.lorem &&
  obj.lorem.ipsum &&
You could use code like this
function get(obj, path) {
    const valueFromPath = path.split('.').reduce((previousValue, pathItem) => {
        if (typeof previousValue === 'undefined') return; // Will finish the rest of the iterations unfortunately :(

        const nextValue = previousValue[pathItem];

        return nextValue;
    }, obj);

    return valueFromPath;

get({foo: {bar: {baz: true}}}, ''); // true
Let me explain the above code. Now whenever we pass the second parameter obj in reduce then the previous value start from there rather from path array. Split is used to change string to array values. Rest of the code is easy to understand you can read more about reduce in mdn docs.

Share this post