0

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
user759235
  • 2,147
  • 3
  • 39
  • 77

2 Answers2

1

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;
    }

John
  • 421
  • 2
  • 5
1

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
DecPK
  • 24,537
  • 6
  • 26
  • 42