Retrieve a specified child object within its parent object using a string identifier

I have a situation where I need to create a JavaScript function that can extract a child object from a parent object based on a specific string identifier.

Here is an example of what I'm looking for:

function findChild(parent, name) {  
  return parent[name];
}

For instance, given the following parent object:

var parent = {
    "key1": "value1",
    "key2": 
        {
            "childKey1": "childValue1",
            "childKey2": "childValue2"
        }
}
var name = "key2"

var childObject = findChild(parent, name)

// Expected result for childObject:
// {
//     "childKey1": "childValue1",
//     "childKey2": "childValue2"
// }

Answer №1

Accessing a property by name in JavaScript doesn't necessarily require a function; it's built into the language's syntax.

object[text]

Answer №2

Consider giving this a shot:

function retrieveProperty(obj, key) {  
    return obj[key];
}

With this function, you can access object properties dynamically using bracket notation rather than statically with dot notation.

Answer №3

To access the property, simply use array syntax:

Object["property"]

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

Issues with implementation of map and swiper carousel functionality in JavaScript

I am trying to populate a Swiper slider carousel with images from an array of objects. However, when I use map in the fetch to generate the HTML img tag with the image data, it is not behaving as expected. All the images are displaying in the first div a ...

Issue with Jquery .ajax function returning an object even after it has already moved on to the next line of code

I'm currently working with JQUERY and AJAX, and it seems like the function is somewhat functional but there's a glitch that occurs after the next line of code runs. This issue causes the script to add a null value when trying to insert the object ...

Is the functioning of closures identical when applied to class methods?

Recently, I started learning React.js (along with Javascript) and I have a basic question to ask. I have created a small component that consists of 3 buttons. Each time these buttons are clicked, the value increments by one. Here is a working example: cl ...

Picture not showing up when loading iPhone video

My website features a video that is displayed using the following code: <div class="gl-bot-left"> <video controls=""> <source src="https://www.sustainablewestonma.org/wp-content/uploads/2019/09/video.fixgasleaks.mp4" ...

Structuring JavaScript in Rails' asset pipeline

Overall: What are the most effective strategies for structuring JavaScript within the Rails pipeline? Specifically: My JS files are growing rapidly and while I'm okay with including them in the main application.js bundle and using Sprockets to minify ...

ReactJS Chatkit has not been initialized

I made some progress on a tutorial for creating an Instant Messenger application using React and Chatkit. The tutorial can be found in the link below: https://www.youtube.com/watch?v=6vcIW0CO07k However, I hit a roadblock around the 19-minute mark. In t ...

The initial request does not include the cookie

My server.js file in the express application has the following code: var express = require('express'); var fallback = require('express-history-api-fallback'); var compress = require('compression'); var favicon = require(&apos ...

What is the best method to handle errors when retrieving JSON data and updating it using fetch()?

I need to figure out a way for the setMessage not to appear when encountering a PUT ERROR 404 not found in the updateTemplate function. I attempted using catch(err) but was unsuccessful. Here is the complete code snippet: My unique version of the code... ...

Google Sheets displaying blank values after submission via an AJAX call

I have been working on transferring data from my web app to a Google spreadsheet and I am encountering some issues. I followed the script provided by Martin Hawksey, which can be found here: https://gist.github.com/mhawksey/1276293 Despite setting everyth ...

Unique patterns on a 3D model in Three.js

I am attempting to replicate the look of the model shown in this photo https://i.sstatic.net/IDLaV.png How can I remove the strange lines from the model while rotating it? You can observe these lines when rotating the model on this link . What seems to be ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

Using the MongoDB aggregate framework to determine the total employee count per unique state

I'm currently working on displaying the total number of employees for each state within companies located in the USA. I aim to showcase this information for all states included in the dataset using sample numbers as a reference: AZ : 1234 CA : 30000 ...

Ajax requests are returning successful responses for GET and POST methods, however, no response is being received for

When I make a POST request within the same domain ( -> ), the responseXML contains the expected data. However, when I make the same request as a PUT, the responseXML is null for a successful request. I have tried using jQuery.ajax and even implemented i ...

Unable to retrieve information from the database during the http.get request

Hey everyone, I've encountered an issue that I need help with. I'm working on retrieving data from a database using an HTTP call and then returning it to the front end. Here's what I have so far: app.get('/contentHandler/post/frontPage ...

Issue with mouseout gap in Microsoft Edge when using the <select> element

A noticeable gap appears in Microsoft Edge between the <select> menu and its options when expanding the menu, as shown here: https://i.stack.imgur.com/SprJ2.png This particular issue can cause problems with the mouseout event due to inconsistent be ...

Is it possible to implement a validation process that prevents the opening of a modal using data-bs-target until all necessary

I am currently using bootstrap version 5.2.3 and I have encountered an issue where the modal opens regardless of validation rules being met or not. I attempted to modify the data-bs-toggle and data-bs-target attributes using Vue.js, but the changes did no ...

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...

Issue with AngularJS: Not able to get second app in template to function properly

I have encountered a puzzling issue with my two nearly identical apps. The first one seems to be running smoothly as expected, while the second one doesn't appear to be executing at all. Here is my code (jsfiddle): <div ng-app="passwdtool" ng-con ...

Creating and downloading a Word document with Node.js by utilizing officegen

Recently, I've been trying to utilize the officegen npm module in order to generate a word (docx) file and then download it. Previously, I relied on the tempfile module to create a temporary path for the purpose of downloading. Below is the code snipp ...

Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows: uploadForm.onsubmit = () => { const formData = new FormData(uploa ...