I am currently attempting to extract data from a JSON file by using key names for reference, but I am running into issues when dealing with nested keys

Is there a better way to retrieve values from a JSON file by matching key names? The current method I am using does not seem to work with nested keys, so any suggestions on alternative approaches would be appreciated.

// Sample .JSON file

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

// Current 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

Answer №1

For accessing nested values, you can utilize the reduce method.

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

Answer №2

If you're looking to access nested properties in an object, you can utilize lodash's get method. Check out the documentation here: https://lodash.com/docs/4.17.15#get.

For those interested in a native implementation, here is the source code for the get method:

 /**
     * A basic version of `_.get` that does not support default values.
     *
     * @private
     * @param {Object} obj The object to query.
     * @param {Array|string} path The path to the desired property.
     * @returns {*} Returns the resolved value.
     */
    function baseGet(obj, path) {
      path = castPath(path, obj);

      var index = 0,
          len = path.length;

      while (obj != null && index < len) {
        obj = obj[toKey(path[index++])];
      }
      return (index && index == len) ? obj : undefined;
    }

    function get(obj, path, defaultValue) {
      var result = obj == null ? undefined : baseGet(obj, path);
      return result === undefined ? defaultValue : result;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on removing the <hr/> tag only from the final list item (li) in an Angular

This is my Angular view <li class= "riskmanagementlink" ng-repeat="link in links"> <h3> {{link.Description}} </h3> <a> {{link.Title}} </a> <hr/> </li> I need assistance with removing the hr tag for the l ...

AngularJS checkbox validation requires a minimum of two checkboxes to be selected

When using AngularJS, I am looking to create a validation rule where a minimum of 2 checkboxes must be checked for the input to be considered valid. Here is what I have attempted: <div ng-repeat="item in items"> <label><input type="chec ...

React.js and Visual Studio Code have recently been causing unexpected and massive "Module not found" errors

Everything was going smoothly with my project until I uploaded it to Github and then cloned it. Suddenly, I started encountering various "Module not found: Can't resolve..." import errors. For example: Module not found: Can't resolve './co ...

Convert JSON to serialize object to string attribute

In a particular scenario, I have classes within an SDK with a complex type hierarchy that I prefer not to modify. Additionally, there is JSON data returned from a service. The issue arises when certain properties in the JSON are returned as objects, while ...

What is the process for sending JavaScript data to a Rails controller action?

Utilizing jQuery Shapeshift for drag and drop reordering of lists on my web application. I am looking to send the data below to my Rails controller action in order to update the list's order. Every time I drag a list, this is the output that appears ...

Is there a way to easily uncheck all MaterialUI Toggle components with the click of a button or triggering an outside

If you have a set of <Toggle /> components in an app to filter clothes by size, and you want to reset all the filters with a single click on a button rather than unchecking each toggle individually. Is it possible to achieve this using materials-ui ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...

Having difficulty uploading an image to Facebook through the graph API

I have a requirement to upload a photo to Facebook using the Javascript SDK, but I am experiencing some difficulties: Firstly, FB.login(function (response) { if (response.authResponse) { va ...

The position of the jQuery VirtualKeyboard is not displaying correctly

I'm currently experiencing an issue with the placement of the keyboard while using the Mottie/Keyboard plugin. The images provided below illustrate my desired outcome and the current behavior: Despite my attempts, the keyboard consistently appears at ...

A guide on clearing the selected value in a dropdown menu with Angular.js

Can someone assist me with setting the drop-down value to blank after completing an action in Angular.js? Below is my code explanation: <div style="height:270px; overflow-x:hidden; overflow-y:scroll;" ng-show="viewOrderTable"> <div class="table-r ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

Is there a JavaScript function available to remove comments from previously commented HTML code?

<div id="div1">bar</div> JQuery function addComment(element){ element.wrap(function() { return '<!--' + this.outerHTML + '"-->'; }); } addComment($('#div1')); Looking for assistance in unc ...

JavaScript script that parses innerHTML

Does the behavior of element.innerHTML = '<script>alert()</script>'; differ across browsers? Can I consistently expect innerHTML to not parse scripts? ...

Can pins be added or removed from a location plan (image or vector) using either Javascript or the DevExpress library?

At the factory where I am employed, there are close to 1000 cameras in operation. I have requested to have the locations of these cameras marked on a non-geographical map of the factory. By simply clicking on one of the camera icons, it should be possible ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Issue: Json variable is not defined

Retrieve States Based on Chosen Country I have set up three select boxes for choosing area, state, and country. The issue arises when I try to fetch city and area information as it throws an error stating "undefined variable" in other scripts that were fu ...

Failed to load Gulpfile.js in the Task Runner Explorer of Visual Studio 2019 version 16.6.2

Displayed below is the result in the output error window. Failed to execute "D:\TortSVN\Oil Diversity\Main Web App\LatsetOildiversity\Gulpfile.js"... cmd.exe /c gulp --tasks-simple fs.js:27 const { Math, Object } = primordials; ...

Receiving Null Value Upon Asynchronous API Call Before Data Retrieval

Struggling with Fetching and Displaying API Data in a Table I am facing a challenge where I need to fetch an API multiple times and populate the data into a table. The issue arises when the data for a specific year is not available, causing the table to b ...

I am new to coding and eager to learn some foundational code to kickstart my journey into programming

Looking to kickstart my coding journey with AI. Any tips would be greatly appreciated. I've experimented with AI generated codes, but am struggling to implement them. I attempted the same codes on the command board, but encountered errors. Any guidan ...