Retrieving the value of an object using an array of keys

Consider the following object:

const obj = {
A:{ 
  a1:'vala1', 
  a2:'vala2'
},
B:{
  b1: 'valb1',
  b2: 'valb2'
},
C:{
  c1:{
    c11:'valc11'
  },
  c2:'valc2'
}
}

We also have an array: const ar = ['C','c1','c11'];

How would you retrieve the value by concatenating the keys from the array? (i.e., obj.C.c1.c11)

Answer №1

If you're looking to retrieve a specific value from a nested object in JavaScript, this function might come in handy. Simply provide an object and an array of keys to pinpoint the desired value:

const obj = {
  A:{ 
    a1:'vala1', 
    a2:'vala2'
  },
  B:{
    b1: 'valb1',
    b2: 'valb2'
  },
  C:{
    c1:{
      c11:'valc11'
    },
    c2:'valc2'
  }
}

const arr: string[] = ['C','c1','c11'];

function getValue(obj, arr: string[]) {
  if ( arr.length === 1 ) {
    return obj[arr[0]];   
  }
  return getValue(obj[arr[0]], arr.slice(1));
}

console.log(getValue(obj, arr));

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

Tips for showing a DialogBox when a blur event occurs and avoiding the re-firing of onBlur when using the DialogBox

Using React and Material UI: In the code snippet provided below, there is a table with TextFields in one of its columns. When a TextField triggers an onBlur/focusOut event, it calls the validateItem() method that sends a server request to validate the ite ...

Is the relevance of Angular 1.x still prevalent in today's development landscape

Considering I have several projects in angular 1.x, I'm contemplating whether it's truly essential and efficient to upgrade them to angular 4 or a later version. The smaller dashboards do not necessarily require an update since they are only use ...

Arranging JSON array in Angular 6 by specific key within the nested array

Is there a way to sort the data object based on the order numbers inside the array objects? data =[ { name:'' list:{ order :2 }, { name:'' list:{ order :1 } ] ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

How can you consistently emphasize data points in a line chart using NGRX?

I'm currently working with a line chart that displays line series. Is there any way to ensure all data points are highlighted at all times? Right now, the only time a data point is highlighted is when the mouse hovers over it. <ngx-charts-line ...

What steps can be taken to troubleshoot the npm start problem?

I am encountering the error shown below: https://i.stack.imgur.com/jqmcF.png This issue is present on Windows but not on Linux. Which dependency do I need to install? I can't seem to locate the Color npm dependency. ...

The element 'x' is implicitly bound with a type of 'any'

I've been exploring the world of Nextjs and TypeScript in an attempt to create a Navbar based on a tutorial I found (). Although I've managed to get the menu items working locally and have implemented the underline animation that follows the mou ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

The function has exceeded the time limit of 60000 milliseconds. Please make sure that the callback is completed

Exploring the capabilities of Cucumber with Protractor has been an intriguing journey for me. As I delved into creating a feature in Gherkin language, outlining the steps and scenarios necessary for my end-to-end tests, a new world of possibilities opened ...

Is there a method for the parent to detect changes in its output when passing around complex objects to its child?

I am facing a challenge with a complex object that is being passed down from a parent component to its child components. The child components further break down this object and pass parts of it to their own children, creating layers of complexity. At times ...

What is the best way to organize the data retrieved from the api into a map?

In my search page component, I display the search results based on the user's query input. Here is the code snippet: "use client"; import { useSearchParams } from "next/navigation"; import useFetch from "../hooks/useFetch&qu ...

In Angular, dynamically updating ApexCharts series daily for real-time data visualization

I am currently working with apexchart and struggling to figure out how to properly utilize the updateseries feature. I have attempted to directly input the values but facing difficulties. HTML <apx-chart [chart]="{ type: ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Using React and TypeScript, open the initial tab from a mapped array with an accordion component

{accordion.map(accordionItem => ( <AccordionItem key={accordionItem.title} text={accordionItem.text} title={accordionItem.title} ></AccordionItem> ...

Exploring the functionality of angular reactive forms in creating intricate JSON structures

After numerous attempts to resolve the issue on my own, I am reaching out to an Angular developer for assistance. My goal is to display a JSON object in the UI: Here is the JSON Object : items={"departure":"New York","arrival":"California","stations":[ ...

Enhance the appearance of the table footer by implementing pagination with Bootstrap Angular6 Datatable styling

I utilized the angular 6 datatable to paginate the data in a table format. https://www.npmjs.com/package/angular-6-datatable Everything is functioning properly, but I am struggling with styling the footer of mfBootstrapPaginator. The items appear stack ...

The implementation of conditional parameter types in TypeScript

I am struggling with a function where the type of the first argument is determined by the second argument's value of true or false According to my logic, if userExists is true, data should be a string and if it's false, data should be a number. ...

Issue with MUI Select custom MenuItem functionality not functioning as expected

Having an issue with MUI's MenuItem in conjunction with Select and rendering it within a separate component. Check out the codesandbox for reference. The setup is as follows: import { Select } from "@material-ui/core"; import CustomMenuIte ...

Is there a way to identify modifications in an Object and an Array when utilized as Input attributes in a sub-component?

After exploring the following two questions, I found that there weren't any helpful answers: Detect change in object of input array Detect changes in component input when it is a object In my current scenario, I am faced with the need to pass variou ...

What is the method to save data into the browser's local storage when the reload button is clicked in AngularJS?

Is there a way to store data into the localstorage in AngularJS when the reload button is clicked? I've tried using the code below, but it doesn't seem to work: window.onbeforeunload = function (event) { var $body = angular.element(documen ...