Retrieve the object property based on an array of indices

I am looking to create a function that can retrieve a specific property of an object based on an array of property names

const getObjectProperty = (arr: string[], object: any) {
  // This function should return the desired object property
}

Expected Outcome:

Let's assume we have this Object

const object = {
  id: 1,
  info: {
    name: "my name",
    age: 21,
    home: {
      city: "New York",
      address: "Street Name"
    }
  },
}

getObjectProperty(["info", "name"], object) // Should return "my name"
getObjectProperty(["info", "name", "city"], object) // Should return "New York"
getObjectProperty(["id"], object) // Should return 1
getObjectProperty(["info", "salary"], object) // Should return undefined

What is the best approach to accomplish this task?

Answer №1

To retrieve a property of an object based on an array of property names, you can utilize a for...of loop to iterate through the array and access the corresponding properties of the object.

const properties = ["details", "title"];

const obj = {
 id: 2,
 details: {
 title: "my title",
 category: "example"
 }
};

let result = obj;

for (const prop of properties) {
  result = result[prop];
}

console.log(result); // "my title"

This task can also be achieved using JavaScript's reduce method in a single line of code:

const finalResult= properties.reduce((result, value) => result[value], obj)

Keep in mind that this code assumes the property names in the array exist within the object structure as nested properties. If there are any typos in the property names or if they do not actually exist in the object, the code will produce an error due to a broken chain of properties.

Answer №2

Remember to utilize the Array reduce method

const arr = ["data", "title"]

const obj = {
  id: 2,
  data: {
    title: "my title",
    age: 30
  }
}

const result = arr.reduce((sum, el) => sum[el], 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

What is the best way to retrieve a specific value in an array object using JavaScript?

I'm working with an array that has the structure shown below: balance = [ {id: 2, is_selected: true}, {id: 4, is_selected: true}, {id: 15, is_selected: false}, {id: 137, is_selected: false}, {id: 30, is_selected: false} ]; Is ther ...

Guide to Including Captions and Spans in a Table

In the given HTML code, nested tables are used by the developer which cannot be changed. However, there is a requirement to replace the table class and add a caption and span only to the main table. <table class="two_column_layout" align="center"> & ...

Unable to figure out a method to properly synchronize a vue.js asynchronous function

I am facing an issue with my code where everything works fine if I uncomment the "return" statement in fetchData. How can I make sure that I wait for the completion of this.fetchData before populating the items array? I have tried using promises, async/awa ...

The illumination in three.js failed to display properly when viewed on Chrome through an Apache server

this illustration shows the issue at hand const directionalLight = new THREE.DirectionalLight(0xffffff, 0.65, 0); directionalLight.position.set(100, -50, 200); scene.add(directionalLight); const ambientLight = new THREE.AmbientLight(0xfff5f3); ...

Is there a way to verify the index in a two-dimensional array in PHP without using a loop?

I have attempted the following code: <?php $list_team = array( (object)array( 'id' => 1, 'name' => 'chelsea.jpg' ), (obje ...

Evaluate a program to identify prime numbers

I am currently working on a JavaScript program that utilizes recursion to determine whether an input is a prime number or not. Within my code, I've defined the isPrime function. The base cases are set to return false when x==1 and true for x==2, cons ...

Retrieve the complete set of elements within the tree branch by identifying the child ID in PHP Arrauu

It's highly likely that this question has been posed before in various forms, but I'm struggling to articulate it effectively. Please bear with me for a moment. In my store script, I have a Category array named $categoryTree where all item categ ...

Leveraging LESS in an Angular2 component

Currently, I am attempting to integrate LESS with angular2. To do so, I have imported the less.js file in my index.html and I am using the following command within the component: less.modifyVars({ '@currentTheme-bar': '@quot ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

How can Angular2 detect when an entity is clicked within a window?

There are multiple items generated using *ngFor: <my-item *ngFor="let item of myArray" [p]="item"></my-item> I am able to handle a click event like this: <my-item ... (click)="doWork(item)"></my-item> However, I want to avoid a ...

What is the best way to set a button as the default option when it is pressed down?

<div class="input-group"> <input type="text" id="srcSchtext" class="form-control" runat="server" placeholder="Search here..." /> <span class="input-group-btn"> <asp:Button runat="server" ID="btnSearchEmployee" ...

Stop Gson's deserialization from causing null values for empty strings

While using Gson to serialize and deserialize JSON, I encountered an issue during testing. It appears that when I provide my Gson object with an empty string, it returns null instead of throwing a JsonParseException. Is there a way to configure Gson so th ...

JS editing an array in a datatable

I have created an HTML page where users can enter data, which is then uploaded to a SQL server. I have been studying DataTables to load an array into a table and tried editing it, but still haven't had success. Can anyone offer assistance? var array ...

Enable an object to be of specific types within a Swagger definition

Currently, I am working on defining an API and one of the fields is named "payload". Previously, this field was defined as "type": string in our Swagger documentation. However, we have noticed that the payload data now has a structured format. Specifi ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Excluding a Spec File in Your Protractor Configurations

I have a scenario where I have 10 spec files all named *********.test.js. I need to run tests on all 9 of these files, excluding the file named Idontwantyou.test.js. Currently, I am locating my spec files in the config.file using: specs: ['*.test.js ...

How can you define the types of function arguments when destructuring arguments in TypeScript?

TS throws an error that states: Error:(8, 20) TS7031: Binding element 'on' implicitly has an 'any' type. Error:(8, 24) TS7031: Binding element 'children' implicitly has an 'any' type. Below is the function I am wor ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Converting a Microsoft Word document into a JSON file

I am looking to convert a document from MS Word format to JSON, possibly through XML first. I am curious about how the parsing and conversion process will handle images embedded in the Word document. How can these images be represented in JSON format? Any ...

The true essence of Angular values only comes to light once the view has been updated

Here is the HTML code I am working with : <div class="container-fluid"> <div class="jumbotron" id="welcomehead"> <br><br><br><br><br><br><br><br><br><br> ...