Is it possible to convert an Object's property into a String resembling "Object.property"?

I am attempting to create a custom function that can convert the keys of an object I am accessing into a string representation. Here is an example:


const test = {
  propertyOne: {
   propertyTwo: 0
  },
  propertyThree: {
   propertyFour: 0
  }
}


function ObjectKeysToString(objectReceived) {
  ...
  return stringfiedObjectReceived
}


Input: 

test.propertyOne.propertyTwo
ObjectKeysToString(test.propertyOne.propertyTwo)



Output: "test.propertyOne.propertyTwo"

Do you think this task is achievable?

I have made efforts to find a solution and explored various Object methods, but unfortunately, none of them have worked for me so far.

Answer №1

Optimally, accessing nested property values in JavaScript usually involves syntax like propertyOne.propertyTwo. Runtime access to variable names is not supported.

const test = {
  propertyOne: {
    propertyTwo: 0
  }
}

function ObjectKeysToString(objectReceived) {
  const path = []
  let current = objectReceived
  do {
    const key = Object.keys(current)[0]
    path.push(key)
    current = current[key]
  } while (typeof current === 'object' && current !== null)

  return path.join('.')
}

console.log(ObjectKeysToString(test))

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 black cube in Threejs is shrouded in darkness, devoid of any unexpected

While exploring a WebGL project, I noticed that other demos have lighting effects present. However, my local code for MeshPhongMaterial on cube 5173 is not displaying the same level of light on all sides. Despite testing various types of lighting options s ...

Experiencing problems with the time format in AM/PM while using moment in a react native

I'm encountering difficulties when it comes to generating AM/PM using moment.js. Currently, both my start time and end time are displaying in the AM format as shown below: https://i.sstatic.net/DtinC.png I would like the end time to be in PM. Any as ...

identify the row preceding the expiration month of a domain using JavaScript or jQuery

Is there a way to highlight the row representing the domain whose expiry month is before the current month, using the date and time information provided in the table (<td>2017-04-14 17:21:00</td>) with JavaScript or jQuery? <table> & ...

How can you initiate the wizard sequence again in TelegrafJS?

I've created a handler function for "/start" that leads to the wizard scene. Now, I have a message with an inline_keyboard containing a button labeled "redo". When I click on the "redo" button, I want it to restart the entire scene, basically initiat ...

The Javascript Switch statement is experiencing some functional issues

I am facing an issue where I need to handle different scenarios based on a decimal value, and I thought of using a Switch/case statement for this purpose. However, the code is not working as expected. Below is the snippet of code in question: var spread ...

Clicking on ng-click doesn't result in opening new windows

I am experiencing an issue with a table where the buttons in the last column are supposed to open a new window but they are not working as expected. Below is the code snippet I am using: <table class="table table-hover" id="angular_table"> <th ...

What's the best way to include user input in an object and showcase the outcomes in React?

I've been developing a CV Application using React, and one of the essential features is the ability for users to input their previous education details, which can then be displayed to potential employers. Users can enter information into an input fiel ...

Angular 2 form validation enhancements

How can I implement a combined validation in Angular2 using OR statements in a Control Group? For example, I have three input fields and I want one to be required, and the other two with an OR requirement. [Input name] = Required, ([Input email] OR [Input ...

I'm feeling stuck trying to iterate through this array, especially when the console keeps saying it's actually an object

As I embark on a personal project to fetch and display information from Reddit, I find myself confused by an error that keeps popping up. There are two main points of confusion for me. The issue arises when the page fails to render due to the message ...

Cloning a repository does not support Typescript compilation

After creating an Angular2 component, I wanted to share the code with my colleagues. Therefore, I uploaded the code to Github, cloned the repository, ran npm install, and then npm run tsc. However, I encountered the following errors: error TS2318: Cannot ...

What is the best way to prevent automatic trimming in EJS variable assignment in Node.js?

When I attempt to write a variable from the database into an EJS table, it is being displayed with default trimming by the EJS template. However, I would like to display the variable from the database without any default trimming. I consulted the EJS temp ...

Using an object as an array index in Javascript

I have been utilizing a crossword application from this specific repository: https://github.com/jweisbeck/Crossword . The issue I am facing is that the program is using jquery version 1.6.2 while my entire project is built on jquery-3.1.1 version. The erro ...

Even though assets are precompiled, the application is still searching for each individual JS file

My Capistrano successfully precompiles all assets in the pipeline and generates the application.js and application.css files. However, my application is still searching for separate .js and .css files that are not on the server, resulting in numerous 404 n ...

Discover the secret to incorporating concealed text in WordPress with a hidden div through the power of JavaScript

For a while now, I've been trying to implement a functionality where clicking on a text reveals a dropdown menu with more information, similar to a "read more" feature. I have limited experience in Java or jQuery, and I can't figure out if the i ...

The JavaScript function is unable to fetch information from the controller

I am working with a controller called Map1 that returns a JSON object. Within my scripts folder, there is a .js file named init.js. In this file, I am attempting to call the controller using the following code: $(document).ready(function() { $.getJSO ...

Activating a div in React.js using setActive: Step-by-step guide

Currently, I am in the process of developing an application with three menu tabs, each represented by an accordion comprising a menu title and content. The issue I am facing is that when clicking on any menu title, all content divs are displayed simultaneo ...

The function() method in Vue.js is executed natively

I have a project where I need to create a simple quiz. Each correct answer should earn 1 point towards the score. Below is the code I am using: let app = new Vue({ el: '#app', data: { crameworks: [ {skor: 0} ], frameworks: [ ...

The functionality of the <select-vue> component in Vue.js does not support null values

custom-select.vue <template> <div class="relative"> <label :for="$attrs.name" class="block text-sm font-medium leading-6 text-gray-900" >{{ $t($attrs.label) }} {{ required ? '*&ap ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

Issue with Responsive Font Size functionality in Tailwind and ReactJS not functioning as expected

I'm really struggling with this issue. I grasp the concept of mobile-first design and have successfully made my website's layout responsive. However, I'm having trouble getting the font size to change when applying breakpoints as the screen ...