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

Is there a way for me to receive the response from the this.$store.dispatch method in vue.js 2?

Here is the structure of my component : <script> export default{ props:['search','category','shop'], ... methods: { getVueItems: function(page) { this.$store.disp ...

Ways to effectively handle diverse Angular module dependencies

Although I am still new to Angular, I have been striving to write more modular code and rely less on cramming logic into the controller. Instead, I have been utilizing independent services. However, a recurring issue I am facing is having to re-declare the ...

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Is there a way to create a function that can show the pathway on the Browser Console?

I am looking to create a function that will show the path in the Browser Console when a link in the menu of a sub-category is clicked. The menu setup resembles this () on an e-commerce website. For instance: Perfume => ForMen => Cologne How can I r ...

Utilizing AngularJS to retrieve associated information from users via a JSON API

I'm currently utilizing the Ionic framework and my inquiry relates to AngularJS. I've set up a JSON API using Ruby on Rails and for authentication, I've opted for ng-token-auth + devise-token-auth. User JSON: { "data": { "id": "1", ...

Tips on showing an api call response in Reactjs

I am a beginner in Reactjs and currently working with nextjs. I have been trying to integrate a "newsletter" feature into my project. I have created a component for this which is functioning properly. However, I am facing an issue with displaying the "succ ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

Where am I going wrong in my attempts to use a callback function?

I am currently attempting to implement a callback function for this particular JavaScript function. function Filtering_GetSite(siteElement) { $.ajax({ type: "POST", url: "samle.asmx/f1", data: "", contentType: "application/json; charset= ...

Using Javascript, populate an array with Enum variable values

Hey there! I've got this code that creates an array from an enum variable in JavaScript, but it's looking a bit old and clunky. I'm curious if any JavaScript or jQuery experts out there have a cleaner (best practice) approach for achieving ...

Attempting to create a functional action listener for a deck of cards game

I'm currently working on a game and want to make an image appear blank when clicked on, to simulate it disappearing. Specifically, this is for a tri peaks solitaire game. I have a function that tests the validity of playing a card, but I'm strugg ...

Tips for choosing a class with a leading space in the name

Struggling with an issue here. I'm attempting to adjust the CSS of a specific div element that is being created dynamically. The current output looks something like this: <div class=" class-name"></div> It seems there is an extra space b ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Experimenting with a Jest test on an express middleware

I'm currently faced with a challenge in testing my controller (express middleware) using Jest. To better illustrate the issue, I will share the code snippet below: import request from 'utils/request'; import logger from 'config/logger& ...

Eliminate any spaces from the JSON string's "outside" keys and values

I have a JSON string saved in a database field that looks like this: {"name" : "John Paul Mark", "surname" : "Johnson"} It's important to note that the name consists of three separate names with spaces between them. I am looking to remove the space ...

Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt. My approach involves using JavaScript and vue.js. Function responsible fo ...

Tips for gathering an array of checkboxes within a dynamic array of items using Vue.js and Vuetify

I am currently working on a role permission system where I have defined a resource array containing items that users can access, as well as checks representing the permissions for each resource. My goal is to dynamically assign a role with these resources ...

developing versatile paths with Node.js

app.js // Including Routes require("./routes")(app); router folder index.js module.exports = function (app) { app.use("/", require("./all_routes")); } all_routes.js var express = require("express"); var route ...

Restrict the selection of dates in the jQuery UI datepicker by disabling public holidays, weekends, the next day after 10am, and only allowing Tuesday, Wednesday, and Thursday as

I found a code snippet on disabling weekends, public holidays, and the next day after 10 am using JQuery UI Datepicker. However, I'm facing an issue where I want to restrict selections to only Tuesday, Wednesday, and Thursday. // JavaScript logic for ...

"Sequelize will pause and wait for the loop to finish before executing the

As someone with a background in PHP, I'm finding the concept of callbacks a bit challenging to grasp. Essentially, I need to retrieve some rows and then iterate through them to compare against another model (in a different database). However, I want ...

What is the best way to ensure that a React app is always displayed in full screen

I am facing an issue while developing an app with React and Material UI. I am trying to display the app in full-page mode, but unable to achieve it successfully. Currently, it appears like this: Here is my code snippet from App.js: import 'typeface- ...