How to access the next nested property of an object in JavaScript

I've been working on a function to retrieve another property key from within the same object.

Consider this example JSON:

'Test123': {
    'Another Test': {},
    'Test some more': {
        'Still testing?': {
            'Yeah...': {}
        },
        'Never ending story': {}
    }
},

For instance, if we input the key 'Still testing?' into the function, it should return 'Yeah...', but if we input 'Yeah...', it should return 'Never ending story'. Does anyone know how to achieve this? I've been attempting to write such a function, but my brain just isn't cooperating...

Answer №1

let data = {
    'Test123': {
        'Another Test': {},
        'Test some more': {
            'Still testing?': {
                'Yeah...': {}
            },
            'Never ending story': {}
        }
    }
}

function findNextKey(lookup, object) {
    if (!lookup || !object || typeof object != 'object' || object.constructor.name != 'Object') {
        console.log("Invalid Input!")
        return
    }
    let isFound = false
    let response = {}
    extractKey(object)

    function extractKey(dataObj) {
        for (let key of Object.keys(dataObj)) {
            if(Object.keys(response).length) return;
            let value = dataObj[key]
            if(key == lookup) isFound = true;
            else if(isFound) {response.key = key; response.value = value; return}
            if (Object.keys(value).length) extractKey(value)
        }
    }

    return (Object.keys(response).length) ? response : "";
}

console.log(findNextKey('Still testing?', data))     //{ key: 'Yeah...', value: {} }
console.log(findNextKey('Yeah...', data))            //{ key: 'Never ending story', value: {} }

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

Creating a recursive function using NodeJS

This particular challenge I am tackling is quite intricate. My objective is to develop a recursive function in NodeJS that can interact with the database to retrieve results. Based on the retrieved data, the function should then recursively call itself. F ...

Utilizing Angular to convert a string array into an array of enum values through an HTTP GET request

I have a list of different user roles defined in my typescript code: enum UserRole { CONSULTANT, MANAGER, ... } There is a REST endpoint /users/id/roles that returns an array of strings representing the roles of a specific user: [ "CONSU ...

Having trouble with saving data when clicking in a react.js app? Check out the codepen link provided for a

I'm currently diving into the world of react.js and tackling a small project. In this project, I'm exploring how to incorporate tagging functionality. The tags will essentially be static text associated with each transaction. My challenge lies in ...

What is the best way to prevent a strikethrough from appearing on the delete button in my JavaScript TO-Do application?

I'm working on coding a to-do app using JavaScript, HTML, and CSS. The issue I'm facing is that when I add the text-decoration: line-through property to the list items, it also affects the X icon used for deleting tasks. I suspect this problem ar ...

How can I generate pure JavaScript, without using Typescript modules?

Take this scenario as an example ... index.ts import { x } from "./other-funcs"; function y() { alert("test"); } x(y); other-funcs.ts import { z } from "some-module"; export function x(callback: () => void): void { z(); callback(); } ...

What is the proper way to insert a line break within a string in HTML code?

Trying to simplify my code, I've turned to using Nunjucks to pass a group of strings to a function that will then display them. This is what it looks like: {% macro DisplayStrings(strings) %} {% for item in strings %} <div>{{ item.strin ...

What is the proper way to designate a manifest.json link tag on a limited-access website controlled by Apache shibboleth?

The issue arises when attempting to access the manifest.json file. It has been declared as follows: <link href="manifest.json" rel="manifest"/> Is it possible to declare the manifest tag inline, or what would be the most effective way to declare it ...

Jackson: A Guide to Extracting JSON Values

String url = "https://ko.wikipedia.org/w/api.php?action=query&format=json&list=search&srprop=sectiontitle&srlimit=1&srsearch=grand-theft-auto-v"; String result = restTemplate.getForObject(url, String.class); Map<String, String> ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

The functionality of JSON.stringify does not take into account object properties

Check out the example on jsfiddle at http://jsfiddle.net/frigon/H6ssq/ I have encountered an issue where JSON.stringify is ignoring certain fields. Is there a way to make JSON.stringify include them in the parsing? In the provided jsfiddle code... <s ...

The accordion seems to be stuck in the open position

Working on a website, I encountered a frustrating bug with an accordion feature. When clicking on the arrow, the accordion opens and closes smoothly. However, when attempting to close it by clicking on the title, the accordion bounces instead of closing p ...

Integrating a real-time chat feature on a website

Considering adding a live chat support feature to my website specifically for new users seeking information about my services. I've been contemplating the most effective way to incorporate this solution without relying on third-party options. My idea ...

Tips for retrieving all values included in the <tr> tags within an html <table>

When the checkbox in the fourth column is clicked, I would like to retrieve all values of td. Additionally, I want to determine the smallest value between ID and Optional ID. <table><form method='GET'> <tr> <th>Name</t ...

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Tips for utilizing GSON and showcasing data in a JSP document

I am in the process of building a web application using JSP. One of the servlet classes I have created is as follows: package managesystem; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; impor ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

Tips for validating a form's input on an ajax page with the help of jQuery

I am facing an issue with a form containing two inputs. The first input can be validated before triggering an ajax function, but the second input cannot be validated. The second input is loaded from a page using ajax, along with the submit button. I need t ...

Regularly check in with the server via ajax calls

I have a page that needs to send periodic "background" ajax requests after it is loaded. These requests should be sent at specific time intervals. Would using cron be the best option for this task, considering that I have never used it before? Are there a ...

Tips for creating multiple files using nodejs and express

I am currently working on developing a personalized code editor that consists of 3 textareas: html, css, and javascript. The objective is to save the data from each textarea into individual files. With the help of express and nodejs, I have successfully m ...

Achieving a Transparent Flash overlay on a website without hindering its usability (attention, interaction, form submissions, etc.)

Currently, we are attempting to overlay a transparent flash on top of an iframe which loads external websites. Is there a method to configure the page in a way that allows the transparent flash to be displayed while still allowing interaction with the und ...