What is the best way to access an element within a child object?

Is there a way to access the value of e without specifying which group, using only obj and e?

Can this method also be used to obtain the value of a?

Appreciate any help!

let obj:Object = {
  a: 'value1',
  b: 'value2',
  group1: {
    c: 'value3',
    d: 'value4'
  },
  group2: {
    e: 'value5',
    f: 'value6'
  }
};

Answer №1

This is my approach to solving the problem:

function getValueFromKey(key, object) {
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            if (prop === key) {
                return object[prop];
            } else if (typeof(object[prop]) == "object") {
                var value = getValueFromKey(key, object[prop]);
                if (typeof(value) !== "undefined") { return value; }
            }
        }
    }
}

getValueFromKey('a', obj);
//"value1"
getValueFromKey('e', obj);
//"value5"

Answer №2

A method to loop through an object's properties is by utilizing Object.keys() and Object.hasOwnProperty() to check for the existence of a property:

const property = Object.keys(myObject)
                .find(key => myObject[key].hasOwnProperty('name'));

console.log(myObject[property].name);

Answer №3

Custom version that handles falsy values as well.

function findValue(key, obj) {
    var val;
    Object.keys(obj).some(function (k) {
        if (key === k) {
            val = obj[k];
            return true;
        }
        if (typeof obj[k] === 'object') {
            val = findValue(key, obj[k]);
            return val !== undefined;
        }
    });
    return val;
}

var newObj = { x: 'val1', y: 'val2', groupA: { z: 'val3', w: 'val4' }, groupB: { u: 'val5', v: 'val6' }, groupC: { m: '', n: 0 } };

document.write(findValue('u', newObj) + '<br>');
document.write(findValue('n', newObj) + '<br>');
document.write(findValue('m', newObj) + '<br>');

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

Display only one dropdown menu at a time

Hey there, I'm currently working on a dropdown menu and struggling to figure out how to keep only one item open at a time. I've tried using an array with useState for all my dropdowns but haven't been able to find a solution yet: code co ...

Importing a MATLAB table file into a Node.js environment and converting it into an array

Currently in the process of setting up a test server for a Web-Application, where fake data needs to be transmitted via a Websocket. The fake data is stored in a MATLAB table file (.mat), which essentially consists of a 4000*192 array. My goal is to conver ...

Populate the content within a div element with specified height and width by utilizing JavaScript and jQuery

I need help with filling a fixed height div with long text retrieved via ajax in json format. For example, if I have a div with a height of 500px and width of 300px, with a font size of 16px. Is there a javascript recursive method that can fill the data ...

In JavaScript, the clearTimeout function may not always return a

Could someone please help me troubleshoot the issue in my code snippet below? I am trying to declare a public variable and assign it to a setTimeout function. If the variable is not null, I want to clear the timeout before setting it again. However, when ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

Switch to a different tab using Bootstrap's navigation tabs and display the corresponding content

I have a regular bootstrap tab panel that allows me to switch between blocks In List 1's content, I included a button called Go to List 2 However, I am struggling to figure out how to make it so that clicking on this button will switch to the List 2 ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Issues with JQuery scroll() / scrollTop() functionality in Internet Explorer and Firefox

Our current script showcases a dotted line starting from the top of the screen leading to an up arrow. The position of the arrow changes based on how far the user has scrolled down the page, allowing them to click on the arrow and scroll back to the top. W ...

Is it possible to integrate AngularJS with jQuery bootgrid?

Despite spending two full days delving into jQuery Bootgrid and AngularJS documentation, I am still struggling to implement angular directives on my dynamically generated grid. My setup involves AngularJS 1.6.6 and jQuery Bootgrid 1.3.1. The page itself i ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Exploring the benefits of integrating JQuery AJAX with non-unicode websites

Using JQuery's '.serialize' and '.post', I am sending form data via ajax to a non-unicode ASP-based website. The resulting data is URL-encoded in unicode, with characters encoded in double values. Is it possible to encode the form ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Choose the initial p tag that includes an image, based on the content of another div

I am trying to figure out how to manipulate the code on my website: <div class="the-post-thumbnail"> <img src="" alt="" width="" height="" /> </div> <div class="post-body"> <p><img src="" alt="" width="" height="" ...

Can you explain the distinction between querying a database and making a request to an endpoint?

Recently, I've been diving into learning mongoose but came across a code that left me puzzled. I'm curious as to why we include the async keyword at the beginning of the callback function when querying a database. Isn't it already asynchron ...

I am unable to populate MongoDB references using Node.js

I need to display the user's location details on the screen. For example: name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy" When the getuser function is called, I want to show the City and Town name. This is the implementation: U ...

How to Modify CSS in Angular 6 for Another Element in ngFor Loop Using Renderer2

I have utilized ngFor to add columns to a table. When a user clicks on a <td>, it triggers a Dialog box to open and return certain values. Using Renderer2, I change the background-color of the selected <td>. Now, based on these returned values, ...

Meteor Routing Issue: The path "/"" you are trying to access does not exist in the routing system

After upgrading Meteor to version 1.3.2.4, I encountered an issue where the error message "Error : There is no route for the path: /" appeared. I made sure to update all packages to their latest versions as well. I tested the application in both "meteor" ...

Unable to employ the inequality operator while querying a collection in AngularFire

I'm facing a challenge with pulling a collection from Firebase that is not linked to the user. While I've managed to query the user's collection successfully, I am struggling to retrieve the collection that does not belong to the user using ...

What could be causing the issue with export default not functioning as expected in this straightforward code?

Whenever I try using export default in the index.js module, it gives me an error message saying: "export 'appReducers' (imported as 'appReducers') was not found in './reducers/index' (possible exports: default). However, when ...

Failure occurred when attempting to link and display on the page container

I have created a simple app using jQuery Mobile. At some point in the app, I include the following code: <a href="test_es.html" data-role="button">Start!</a> This code snippet loads a new HTML file that contains several jQuery Mobile page ...