JSFiddle - React, Tailwind, and code Playground

by Vladymyr Shevchuk

JavaScript

const obj = {
	foo: {
  	bar: {
    	baz: 1
    }
  }
};

const createGetter = (fieldsPath) => {
	const separator = '.';
	const pathArr = fieldsPath.split(separator);
  
  return obj => {
  	let result;
  
    pathArr.forEach(path => { 
	    if (result && result[path]) {
      	result = result[path];
      } else {
      	result = obj[path];
      } 
  	});
  
  	return result;
  }
};

const createGetterViaRecursion = (fieldsPath) => {
	const separator = '.';
	const pathArr = fieldsPath.split(separator);
  
  return obj => {
		const getProp = (nestedObj, path) => {
	    return pathArr.length 
      	? getProp(nestedObj[path], pathArr.shift()) 
        : nestedObj[path];
    };
  
  	return getProp(obj, pathArr.shift());
  };
};


const getter = createGetter('foo.bar');
const value = getter(obj);

console.error('value', value);