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

Guide to importing the Slider Component in React using Material-UI

I am trying to incorporate the Slider Component from @material-ui/core into my React project. However, when I attempt to import the Slider using this code: import Slider from '@material-ui/lab/Slider';, it gives me an error stating Module not fou ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

How to Troubleshoot VueJS Component Render Issues After Importing/Calling Components

In one of my projects, I successfully implemented a file uploader component using import and component statements. import fileUploader from '../common/FileUploader.vue'; Vue.component('file-uploader', fileUploader); This implementation ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Issues with the functionality of the Handlebars template are causing it to

Currently experimenting with Handlebars templates within my express/node.js application. I have created a template and corresponding .js files, but unfortunately, they are not functioning as expected. While the page correctly displays the unordered list&ap ...

Comparing the efficiency of using arrays versus mapping to an object and accessing data in JavaScript

When considering the basics of computer science, it is understood that searching an unsorted list typically occurs in O(n) time, while direct access to an element in an array happens in O(1) time for HashMaps. So, which approach yields better performance: ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

Storing data from a massive JSON array into a separate array using a specific condition in JavaScript

Dealing with a large JSON array can be challenging. In this case, I am looking to extract specific objects from the array based on a condition - each object should have "dbstatus":-3. data = [{"id":"122","dbstatus":-3},{"id":"123","dbstatus":"-6"},{"id" ...

What is the reason for the absence of Duplex Stream in the Web Streams API?

I have experience working with the traditional nodejs stream, which makes the need for Duplex streams quite evident. These are streams that can both read and write data, like net.Socket. As mentioned here Examples of Duplex streams include: TCP sockets ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

Is it possible to execute a specified quantity of Promises simultaneously in Nodejs?

Currently, I am working on developing a web scraping application that utilizes a REST API to gather information from multiple entities on the server. The core functionality of this application can be summarized as follows: let buffer = [] for(entity in ent ...

Swap out The div element with the html() method

I'm encountering an issue when trying to swap out a div element with ajax. My goal is to create a start/stop button functionality. The page displays a list of card elements, each with its own button, which are stored in separate html files. work_orde ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

Utilizing a backup system to store environment variables within a configuration file

Currently, I am utilizing my environment variables by directly referencing process.env.NODE_ENV throughout my application. While this method works, it is becoming challenging to manage and keep track of. Therefore, I would like to consolidate all these var ...

When Retrofit Response does not contain any data within the body

I am currently using retrofit to retrieve data from an HTTP URL. Here is my Interface Class : public interface SlotsAPI { /*Retrofit get annotation with the specified URL And our method that will return a JSON Object */ @GET(url) re ...

Flask-SocketIO: Transmitting data between nodes using Redis adapter

When integrating SocketIO into an application running behind a node-balancer, the documentation recommends using SocketIO-Redis to facilitate event passing between nodes: const io = require('socket.io')(3000); const redis = require('socket.i ...

Unexpected outcome from the zero-fill operator (>>>) in Javascript's right shift operation

Initially, is (-1 >>> 0) === (2**32 - 1) possibly due to extending the number with a zero on the left, transforming it into a 33-bit number? However, why does (-1 >>> 32) === (2**32 - 1) as well? I had anticipated that after shifting the ...

Having trouble testing firebase messaging on my local server

I've encountered an issue while trying to retrieve a token from firebase/messaging for use in notifications. The error message "messaging/unsupported-browser" (FirebaseError: Messaging: This browser doesn't support the API's required to use ...