Retrieve the property value from a nested object using a key that contains spaces

Presenting my object:

let obj = 
{
    innerObj: {
        "Key with spaces": "Value you seek"
    }
}

Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows:

let key = "innerObj['Key with spaces']";

How can I utilize this string variable to extract the value from the object?

The apparent solution, which unfortunately fails:

obj[key]; // results in undefined

Update: Hoping for a more versatile resolution than just this specific scenario. For instance, I might need to delve further into nested levels, possibly encountering dot notation. I am utilizing angular.js and considering there may be built-in functionality for such operations.

Answer №1

  1. Divide the string using [' as a delimiter
  2. The initial segment will be nestedObj - this represents the name of the first nested object
  3. The second part is My key has spaces']; we will eliminate '] from the end by replacing it with an empty string; now we have the property of the nested object - precisely what is required

var theKey = "nestedObj['My key has spaces']";

myObj[theKey.split("['")[0]][theKey.split("['")[1].replace("']","")];

Demonstration:

var myObj = 
{
    nestedObj: {
        "My key has spaces": "You want my value"
    }
}

var theKey = "nestedObj['My key has spaces']";

var result = myObj[theKey.split("['")[0]][theKey.split("['")[1].replace("']","")];

alert(result);

Answer №2

Here is a suggestion to consider:

execute('myObj.' + keyValue); 

Answer №3

UPDATE: Enhanced response for the revised inquiry :)

To view the code in action, check out this JsFiddle link

Utilizing regular expressions:

var example1 = "nestedObj['My key has spaces']";
var example2 = "abc [\"def ghi\" ].jkl[123][ 'mn o']";

function extractKeys(input) {
    var regExpressions = [
        /^\s*\[\s*(\d+)\s*\]/,         // Scenario 1: [ someIntegerKey ]
        /^\s*\[\s*\'([^\']+)\'\s*\]/,  // Scenario 2: [ 'someKey' ]
        /^\s*\[\s*\"([^\']+)\"\s*\]/,  // Scenario 3: [ "someKey" ]
        /^\s*\.\s*([^\[\.]+)/          // Scenario 4: . someKey
    ];

    var keysArray = [];
    var remainingStr = "." + input;
    var successStatus = true;

    while (successStatus) {
        var resultMatch = 
            remainingStr.match(regExpressions[0]) || 
            remainingStr.match(regExpressions[1]) ||
            remainingStr.match(regExpressions[2]) || 
            remainingStr.match(regExpressions[3]);

        if (resultMatch) {
            keysArray.push(resultMatch[1]);
            remainingStr = remainingStr.slice(resultMatch[0].length);
        } else {
            successStatus = false;
        }
    }

    return keysArray;
}

console.log(extractKeys(example1));
console.log(extractKeys(example2));

Answer №4

To simplify the process, using a basic array of strings can be effective. Here's a concise code snippet for achieving this task (originally shared by me in another answer):

function get(obj, property) {
  var current = obj;
  for (var i = 0, l = property.length; i < l; ++i) {
    if (Object(current) === current) current = current[property[i]];
    else {
      current = undefined;
      break;
    }
  }
  return current;
}

For example:

get(obj, ['nestedObj', 'My key has spaces']); // "You want my value"

If the property is not found, the function will simply return undefined. However, it's easy to modify the code to throw an error according to typical JavaScript behavior when accessing a property on undefined or null.


In case you prefer using the exact property string syntax, a parser I developed previously may come in handy, although it's quite basic. This parser employs regular expressions to extract segments from the string and assemble them into an array. It then traverses the array to locate nested values within an object passed as input.

The parsing algorithm accommodates escape sequences, strings, plain numbers, and dot property access. The only limitation lies in referencing actual variables and utilizing invalid identifiers at the beginning, which I am currently working on resolving.

Here's an illustration:

evaluateProperty({ test: { 'space space': 1 } }, 'test["space space"]'); // 1

The script used for parsing:

function parsePropertyString(str) {
  // Code for parsing goes here...
}

function evaluateProperty(obj, str) {
  var propertyChain = parsePropertyString(str);
  for (var i = 0; i < propertyChain.length; ++i) obj = obj[propertyChain[i]];
  return obj;
}

// Additional regex creation to optimize performance
function createStrRegex(type) {
  return new RegExp(
    '^' + type + '(?:[^' + type +
    '\\\\\\r\\n\\u2028\\u2029]|\\\\(?:[^xu\\d\\r\\n\\u2028\\u2029]|0(?!\\d)|x[\\da-fA-F]{2}|u[\\da-fA-F]{4})|(?:\\r\\n|[\\r\\n\\u2028\\u2029]))*?' +
    type + '$'
  );
}

var singleQuoteStr = createStrRegex("'");
var doubleQuoteStr = createStrRegex('"');

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

Displaying threaded discussions in React

Below is an array that contains comments, and I am attempting to display them in a threaded manner by utilizing the parentId property. comments: [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3 ...

javascript hide rows without data

I have a knack for tweaking existing code to suit my needs, but I'm not very proficient in writing my own from scratch. That being said, here's my current dilemma. My pool league uses a Google sheet to manage a variety of statistics, and with so ...

Guide to using the PUT method in Node.js Express to update a record using the primary key

I'm currently struggling with understanding the proper usage of the put statement in node js. Here is the code I have been using: app.put("/cars/:id", (req, res) => { //retrieving a record based on id (uuid) e.g. http://localhost:3000/cars/a5ad957 ...

What is the best method for gracefully opening external links in a reusable new tab?

Here is the progress I have made so far: <script> var win; function OpenInNewTab(url ) { // var win; if (win) { win.close(); } win =window.open(url, 'myWin'); win.focus(); } </script> My links are structured like ...

Impose a delay between the execution of two functions in React.js

Looking for a way to introduce a forced delay between two consecutive function calls. Essentially, what I want to achieve is: a // call func a delay(100) // pause for 100 ms b // call func b Is there a method to accomplish this? Update: attempted a() ...

Error encountered while trying to access OData feed in Tableau 8.1 due to incorrect OData format

Having difficulty connecting to an OData feed, I keep receiving this error message: "Bad OData Format. Ensure you are using a URL that directs to a valid OData Source." I am able to access the URL in a browser (and receive the correct JSON response), and ...

The Watchdog API detects a change in the path to monitor, resulting in double triggering for a single update

import os import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import docker import json import configparser class FileChangeHandler(FileSystemEventHandler): def on_modified(self, event): if event.is ...

Using JavaScript to browse and filter by category

After spending some time working on a search function, I received some assistance from Tim Down who provided me with a simple code to search for specific text within a page. Now, my goal is to modify the code to enable searching by category. I have struct ...

Is there a way for me to have a table automatically scrolled to a specific column upon loading the HTML page?

My table contains a dynamic number of columns based on the months inputted from the database starting from a start_date and ending at an end_date. I have the current_date stored as a variable and want the table to load with the x-scrollbar positioned right ...

Enhance the efficiency of DataTable by optimizing cell class modifications

I have been very pleased with the performance of jquery DataTables, but I have encountered a situation where I need to optimize it further. Specifically, I am updating the class of a cell based on its data. Currently, I am achieving this by using the ren ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Learn how to swap out the traditional "back to top" button with a customized image and make it slide onto or off the page instead of simply fading in and out

As a newcomer, I am trying to replicate a unique "back to top" effect that caught my eye on another website. Instead of the traditional fade-in approach when scrolling down, the "back to top" image in question elegantly slides out from the bottom right c ...

strange occurrences in localToWorld transformation

Hello there! Currently, I'm working on a project where I'm generating a TextMesh using font geometry and placing it within an empty pivot object. My goal is to obtain the world coordinates of each vertex in the TextMesh so that I can manipulate ...

Having trouble dynamically adding elements to the Semantic-UI Accordion component

I have a challenge involving inserting dynamic content into a Semantic-UI Accordion. My goal is to display JSON data as an Accordion in the HTML. Below is the script and HTML I am using for this purpose: <script language='javascript'> ...

Is your prop callback failing to return a value?

I am currently utilizing a Material UI Table component in my ReactJS project and I would like to update a state variable whenever a row is selected or deselected. The Table component has an onRowSelection prop that gets triggered each time a row is is sele ...

When attempting to debug JavaScript in Edge with Visual Studio Code, an error message stating 'Failed to load source map for chrome-error...' was encountered

Attempting to troubleshoot JavaScript code in Visual Studio Code is resulting in an error: Could not read source map for chrome-error://chromewebdata/: Unexpected 503 response from chrome-error://chromewebdata/edge-elixir-neterror.rollup.js.map: Unsupporte ...

Is it possible to create Android apps using HTML and JavaScript?

I have a strong foundation in HTML, Javascript, CSS, and AJAX, but I want to venture into Android application development. However, I lack knowledge of Java technology. Is it feasible to develop Android apps using HTML or JS? If anyone has experience wit ...

Navigating a JSON array using the Handlebars template engine

I have a JSON file and I am looking for guidance on how to display the information from it using the handlebars template engine: This is the template code: <script id="template-app" type="text/x-handlebars-template"> {{#each data}} Emai ...

The error code 13:5 indicates that the "Home" component has been registered in the Vue application but is not being used, leading to the error message "vue/no-unused-components"

I encountered this issue while working with Vue for the first time. I was attempting to construct a website using Vue/CLI by reorganizing and building from the inside out. However, I am unfamiliar with Vue and unsure how to resolve this error. The changes ...

What is the best way to transform a JSON string into a JavaScript array within a JSP file

Below is the code in my JSP. How can I access the variable (String jsonname) as a JavaScript array? Currently, it is not printing anything. ArrayList<String> name=new ArrayList<String>(); name.add("Ravi"); name.add("Vijay"); name.add ...