Accessing multiple nested objects in Javascript using a string as an object reference

One thing I am aware of is the ability to define an object reference from a string, such as this:

obj['string']

This essentially translates to obj.string.

My query arises when trying to extend this beyond the first object value. This is what I would like to achieve:

obj['string1.string2']

Unfortunately, this fails because the key (string1.string2) does not exist within the object. While I understand how this works, my struggle lies in figuring out how to make it work and return obj.string1.string2.

The specific scenario that I am dealing with involves an array of objects:

let players = [
  {
     name: 'Player 1',
     points: {
       current: 100,
       total: 1000
     }
  },
  {
     name: 'Player 2',
     points: {
       current: 50,
       total: 500
     }
  }
];

I am attempting to sort the array based on the current value of points using players.points.current.

The sorting method I have implemented is as follows:

players.sort((a, b) => { return b.points.current - a.points.current });

While this method works effectively, I am exploring ways to create a function that can accept a 'sorting' term in string format like points.current or points.total, aiming to enhance reusability and reduce code repetition. In my efforts to pass the string into the object reference, I encountered the issue where the key does not match any existing values: players['points.current']

I would sincerely appreciate any help or guidance offered by individuals who could assist me in this matter. Should I approach this dilemma from a completely different perspective?

Answer №1

To concatenate the properties, you can utilize dot notation where everything enclosed in quotes is treated as a single property name string like this:

object['thing1']['thing2']

If you need to make it work with a string having an unknown number of nested properties, you would iterate over each one. It's a bit tricky to explain but here is an example:

let obj0 = {
    obj1: {
       obj2: "answer"
  }
}

let string1 = "obj1.obj2"

let strArr = string1.split('.')

let objSearch = obj0;

strArr.forEach(str => {
    objSearch = objSearch[str]
})

console.log(objSearch)

Remember, this method only functions correctly when the object properties actually exist. It is advisable to incorporate some error handling for cases where objSearch[str] may not exist.

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

Instead of properly addressing the issue, the error message "Cannot read property 'password' of undefined" is being displayed

I'm currently working on creating a user login system using express js and dynamodb. However, I'm facing an issue where the system works fine when logging in with correct email and password, but fails to handle errors when using an incorrect emai ...

Learn how to utilize the Angular reactive form to set default values based on a previously saved object

My work on the reactive form is almost complete, with all basic logic in place. However, I am facing a single issue that is holding me back. As per the requirements, all input fields should be pre-filled with previously entered data by the user, if availab ...

Just getting started with jQuery and looking for assistance with adding elements during events

My current project involves creating a button that, when clicked, updates a 'feed' div. The goal is to generate three elements: a tweet(<div>), a message(<p>), and a username(<p>). These elements should be added to the tweet div ...

Personalized modify and remove elements on a row of the DataGrid material-ui version 5 component when hovered over

In my React Js app, I am utilizing Material UI components or MUI v5 as the UI library for my project. Within the DataGrid/DataGridPro component, I am implementing a custom edit and delete row feature. The requirement is to display edit and delete icons w ...

What's the Solution to Repairing This For Loop within the Array?

Below are the instructions for the task at hand: "The array testGrades holds the scores of NUM_VALS tests. Create a for loop that calculates sumExtra, which is the total extra credit earned. Any score over 100 counts as extra credit. For example, if testGr ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

Using Typescript with Protractor for Dropdown Menus

As a newcomer to Protractor, I am looking to automate the selection of a dropdown. While I have some knowledge in JavaScript, I am currently working with typescript. Can someone advise me on how to select the dropdown option based on the text provided? Fo ...

Struggling to set up a Node three.js website on a server, looking for guidance on the process

I am encountering an issue with uploading my files to the public_html folder on the server. The application consists of an HTML file, a three.js JavaScript file, and other supporting files. To run the application, I need to type "npm i" and then "npm run d ...

Combining associative arrays by utilizing a mapping array along with an array containing partial keys (providing support for named parameters)

Exploring a new template system I am creating, one that specifically caters to named parameters in template filters and functions. Let's cut to the chase and address the issue at hand using my escapeHtml filter, which essentially mirrors htmlspecialc ...

Maintain the chosen month in every dropdown toggle div in angular 4

While displaying data using toggle options, I am facing an issue where if I click on a different month, all other greyed out headers are displaying the previously selected values. I am trying to figure out a way to keep the value under Selected month as i ...

Angular ForkJoin() Problem Encountered

Hello, I am currently designing a User Interface and I need to display a unique JSON response value for each 'digId'. In the example below, there are 3 incidents and I used forkJoin to access the 3 JSON responses. digId='4149'; ...

Unable to run the method in the parent component from the child component

I am attempting to trigger a method to run on a parent component when a button within one of its child components is clicked. I am utilizing single file components with Webpack. Below is the code for the child component: <template> <button v-on ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

What is the best way to send events to connected sockets using socket.io directly from my Express 4 routes?

I have a question that others have asked before, but I'm struggling to benefit from their answers due to the unique Express setup I have. Currently, I have socket.io implemented and running smoothly on my server in a simple manner. Here is how it is ...

What is the best way to automatically scroll to the chosen option when a button is clicked?

Is there a way to make the select box automatically scroll and show the selected option when the focus button is clicked? The current method I am using with focus does not achieve this. Are there any JavaScript or jQuery methods that can help me solve th ...

What is the best way to create a new row within a Bootstrap table?

Struggling to format an array inside a table with the `.join()` method. The goal is to have each car on a separate row. Attempts using `.join("\r\n")` and `.join("<br />")` have been unsuccessful. What am I overlooking? ...

Encountering an issue when transferring data between controllers utilizing a demo service

During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this: The Controller Code <!DOCTYPE html> &l ...

There was a problem encountered during the serialization process to JSON

Hey there, I'm encountering an error when trying to Serialize JSON. I have a model with a List property; MyModel: public virtual int Code { get; set; } public virtual string Name { get; set; } public virtual string TrafficCode { get; set; } ...

I've noticed that my alert is not appearing when I click submit. Can someone please help me figure out what I could

I am having trouble getting my alert to display when the form is not validating. It should show an alert message if the form is valid but it's not working as expected. I've spent hours trying to fix this issue with no luck. I appreciate any help ...