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

Angular Search Version 2.0

I am facing an issue with my search functionality in Angular 2. When I type into the search box, the search method on the service is not triggered. I believe there might be a simple solution that I am missing. Any assistance would be greatly appreciated. ...

Using the spread operator in the console.log function is successful, but encountering issues when attempting to assign or return it in a

Currently facing an issue with a spread operator that's really getting on my nerves. Despite searching extensively, I haven't found a solution yet. Whenever I utilize console.log(...val), it displays the data flawlessly without any errors. Howev ...

Tips for identifying and handling errors in Playwright

I'm going crazy trying to handle a TimeoutError that I know is coming. Currently, I'm testing the Hidden Layers scenario from UI Testing Playground in Playwright Node.js and I want to see if there's a way to prevent the TimeoutError from cau ...

Ways to address the issue arising from the utilization of the "as" keyword

Every time I encounter this issue - why must I always provide all the details? type Document = Record<string, any> type FilteredDocument<T extends Document> = {[key in keyof T as T[key] extends (()=>void) ? never : key]: T[key]} const ...

TypeScript is failing to identify a correctly typed property

Currently, I am facing issues while converting a Material UI Dashboard from React to Typescript. The problem arises during TypeScript compilation where the property in question meets the criteria mentioned in the error message. To put it briefly, the compi ...

Using a Component as a Property in Angular

There is a small gridComponent: @Component({ selector: 'moving-grid', templateUrl: './grid.component.html', styleUrls: ['./grid.component.css'] }) export class GridComponent { @Input('widgets') ext ...

What is the best way to output the leaf nodes from an array of object lists in TypeScript?

Having trouble with TypeScript, specifically working with arrays and filtering out leaf nodes. I want to print only the leaf nodes in the array, resulting in ['002', '004', '007']. Can someone please assist me? Excited to lear ...

tips on rotating an image using nativescript

I'm attempting to insert a picture from my device and then adjust its orientation in nativescript. So far, I've been using imageSource to import the picture, but I'm unsure how to rotate it. If anyone has suggestions for another class that c ...

Is it possible to dynamically adjust the size of the CircleProgressComponent element in ng-circle-progress?

For my current Angular 11 project, I am facing the challenge of dynamically changing the size of the ng-circle-progress library's CircleProgressComponent element. After some research, I discovered that the element's size can be adjusted by apply ...

Learn how to dynamically add a class name while iterating through an array of objects using ngFor

As I loop through an array of objects, I encounter entries in the form: { name: 'filename', order: '', open: true, isEditOn: false, tempVal: '', id: 0} My goal now is to dynamically assign a class to the div based on the obj ...

Ways to avoid Next.js from creating a singleton class/object multiple times

I developed a unique analytics tool that looks like this: class Analytics { data: Record<string, IData>; constructor() { this.data = {}; } setPaths(identifier: string) { if (!this.data[identifier]) this.da ...

Protractor end-to-end tests fail to run properly when the `--spec` flag is utilized

Currently, I am running 'ng e2e' on an Angular CLI project and I am looking to specify a specific test to run instead of running all of them. When I execute ' ng e2e --aot ', the test runs smoothly. However, when I try ' ng e2e ...

How can one trigger a service method in nestjs through a command?

I am looking to run a service method without relying on API REST - I need to be able to execute it with just one command ...

Encountering a 405 error when making an OpenAI API call with next.js, typescript, and tailwind CSS

I encountered a 405 error indicating that the method request is not allowed. I am attempting to trigger an API route call upon clicking a button, which then connects to the OpenAI API. Unsure of my mistake here, any guidance would be highly appreciated. E ...

What is the best way to pass dynamic values to a service constructor from a component?

After days of attempting to grasp 'the Angular paradigm', I still find myself struggling to understand something about services that are not singletons. It seems impossible for me to pass a runtime-determined value to a service constructor, as I ...

Submitting a value to ngForm: A step-by-step guide

I am working on an ngForm within Angular Material that contains several input fields. I want to include a new field called total in the submission, but this field is not an input field. It should be a readonly field and its value needs to come from the Typ ...

Tips for accessing a Literal type in TypeScript instead of a Union type

I recently developed a function to generate dynamic elements. However, I encountered an issue where instead of returning the precise type of the element, it was producing a union of various <HTMLElementTagNameMap> types. function createCustomElement( ...

Leverage a unified custom theme across both iOS and Android platforms in Ionic 3

My Ionic application displays distinct widgets for the iOS and Android platforms. What is the most effective method to maintain customized buttons, input boxes, etc., that are consistent across both platforms? How can I create a unified theme for all plat ...

Issue with importing aliases in Angular 7 production environment

Hello everyone! I have encountered an issue where using alias on import and building the project in production mode (--prod flag) results in the alias being undefined. Interestingly, this behavior does not occur in development mode. Any suggestions on how ...

What causes the typescript error in my code: The argument being passed is either a string, an array of FilterData, an array of numbers, or an array of Moments, which is not compatible with a parameter of type 'string'?

When writing my code, I have the need to utilize various types for different scenarios. Depending on the situation, the type may be a string, number[], FilterData[] (a custom type), or Moment[]. To address this requirement, I defined the type as: export ty ...