I am trying to get values from an JSON file by matching key names, but it does not work with nested keys

I am trying to key values from an JSON file by matching key names, but it does not work with nested keys, maybe not the best way to load date this way(if there are better ways to do this let me know).

// .JSON file

{
    "routes":{
        "path":{
            "register":{
                "index": "register"
            },
            "login":{
                "index": "login"
            }
            ...
        }
    }
}

// solution(not working)

const paths = require(`../locales/en-US.json`)
const getByValueByKey = (getPath, value) => {
    for (let key of Object.keys(getPath)) {
        if (getPath[key] === value) {
            return key;
        }
    }
}

getByValueByKey(paths, 'routes.path.login.index')//should return login

2 answers

  • answered 2021-06-10 11:04 John

    You can use lodash's get method - https://lodash.com/docs/4.17.15#get.

    This is the source code for that method if you want a native implementation:

     /**
         * The base implementation of `_.get` without support for default values.
         *
         * @private
         * @param {Object} object The object to query.
         * @param {Array|string} path The path of the property to get.
         * @returns {*} Returns the resolved value.
         */
        function baseGet(object, path) {
          path = castPath(path, object);
    
          var index = 0,
              length = path.length;
    
          while (object != null && index < length) {
            object = object[toKey(path[index++])];
          }
          return (index && index == length) ? object : undefined;
        }
    
        function get(object, path, defaultValue) {
          var result = object == null ? undefined : baseGet(object, path);
          return result === undefined ? defaultValue : result;
        }
    
    

  • answered 2021-06-10 11:05 decpk

    You can use reduce and get the value.

    const result = value.split(".").reduce((acc, curr) => acc && acc[curr], getPath);
    

    const paths = {
      routes: {
        path: {
          register: {
            index: "register",
          },
          login: {
            index: "login",
          },
        },
      },
    };
    
    const getByValueByKey = (getPath, value) => {
    const result = value.split(".").reduce((acc, curr) => acc && acc[curr], getPath);
      console.log(result);
    };
    
    getByValueByKey(paths, "routes.path.login.index"); //should return login