approach for extracting values from nested objects using specified key

There are objects in my possession that contain various nested objects:

let obj = {
 nestedObject: {
  key: value
 }
}

or

let obj2 = {
 nestedObject2: {
  nestedObject3: {
   key2: value2 
  }
 }
}

and so on.

Retrieving the values from these objects is straightforward:

obj.nestedObject.key 
obj['nestedObject']['key']

or

obj2.nestedObject2.nestedObject3.key2
obj2['nestedObject2']['nestedObject3']['key2']

However, I need to handle this dynamically for any object structure that comes my way. I receive random objects with the same format and a string indicating where to locate the values. For example, for obj2 in the sample above, I would receive the string:

"nestedObject2.nestedObject3.key2"

How can I utilize this information to retrieve the desired value? The methods used previously no longer apply, and attempts like:

obj2['nestedObject2.nestedObject3.key2']

do not yield the expected results.

Answer №1

To extract the desired property, split the string using a period as the delimiter and then use the reduce method to navigate through nested objects.

str.split(".").reduce((accumulator, value) => (accumulator = accumulator[value], accumulator), parent_object);

let obj = {
    firstNestedObject: {
      secondNestedObject: {
        key: "value"
      }
    }
  },
  str = "firstNestedObject.secondNestedObject.key";

let result = str.split(".").reduce((accumulator, value) => (accumulator = accumulator[value], accumulator), obj);

console.log(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

The image file that was uploaded from a React Native iOS application to Azure Blob Storage appears to be corrupted or incomplete as it is not

Struggling to develop a feature in a React Native mobile app where users can upload and crop their profile picture, then store it in Azure blob storage. I encountered difficulty with implementing react-native-fs as many resources recommended it, but I kep ...

JavaScript: a single function and two calls to Document.getElementById() results in both returning "undefined"

Within my JavaScript file, I have a function that utilizes two variables: choice and courseChosen. The latter variable must be converted into an object first. In the HTML, the tags courseName and courseInfo are used for choice and courseChosen respectively ...

Ways to retrieve information from a different website's URL?

Having a bit of an issue here. I'm currently browsing through some reports on webpage #1 () and I have a specific requirement to extract the object named "data" from webpage #2 (). However, the code I've used seems to fetch the entire webpage ins ...

How can you make each <li> in an HTML list have a unique color?

Looking for a way to assign different colors to each <li> element in HTML? <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <ul> Here's how you want them displayed: Item 1 should be red Ite ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

Steps for uploading an item to an API using an Excel document

I'm facing an issue where I am trying to send a large object along with an Excel file to an API. However, only my photo is being recognized and the object is not sent, resulting in an [object Object] error. I understand that this error occurs due to i ...

JavaScript is experiencing an error where it cannot define a function, rendering it unable to generate a JSON object due to its inability to recognize that the

I've created a JavaScript script function that holds cart items for ordering food. This function takes two parameters: ID and price. Here is a snippet of my script file: <script> function addtocart(mitem, mprice) { var price = ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

What could be causing the strange output from my filtered Object.values() function?

In my Vue3 component, I created a feature to showcase data using chips. The input is an Object with keys as indexes and values containing the element to be displayed. Here is the complete code documentation: <template> <div class="row" ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

What is the best way to generate script code dynamically on an HTML page depending on the environment?

I am facing a challenge with my asp.net application. I need to insert a dynamic script into the html section, and this script's value must change depending on the environment (TEST, QA, etc.). To illustrate, here is the script where DisplayValue is th ...

"Hiding elements with display: none still occupies space on the

For some reason, my Pagination nav is set to display:none but causing an empty space where it shouldn't be. Even after trying overflow:hidden, visibility:none, height:0, the issue persists. I suspect it might have something to do with relative and ab ...

Do you think my approach is foolproof against XSS attacks?

My website has a chat feature and I am wondering if it is protected against XSS attacks. Here is how my method works: To display incoming messages from an AJAX request, I utilize the following jQuery code: $("#message").prepend(req.msg); Although I am a ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...