Retrieving object properties dynamically using an array of strings

I am attempting to dynamically access an object property from an array of strings that contain the path to the desired value. Currently, it only accesses the first index ('Properties') and returns 'undefined' for the rest. I am expecting the output to be "ES_STUE".

let objPath = ["properties.Constraints.Level"];

const object = {
  properties: {
    Visibility: {
      "Tender Code": "",
    },
    Data: {
      DTU_ClassificationNumber: "",
      DTU_InformationAccuracy: "",
    },
    "Model Properties": {
      "Workset (Manual)": "No",
    },
    Constraints: {
      Level: "ES_STUE",
      Host: "Level : ES_STUE",
      "Offset from Host": "0.000 mm",
      "Moves With Nearby Elements": "No",
      "Default Elevation": "0.000 mm",
    },
  },
};

for (const iterator of objPath) {
  const keySegment = iterator.split(".");
  for (const prop of keySegment) {
    console.log(prop);
    const result = object[prop];
    //const result = object["Properties"]["Constraints"]["level"] not sure if this is correct
    console.log(result); // should return "ES_STUE"
  }
}

Answer №1

Strategy

  • Begin by breaking down the `objPath` string.
  • Iterate through each element in the split array.
  • As you iterate, update the `result` node using the value of `result[prop]` where `prop` represents the key.
  • This process allows for drilling down into the object during each iteration.

let objPath = ["properties.Constraints.Level"];

const object = {
  properties: {
    Visibility: {
      "Tender Code": "",
    },
    Data: {
      DTU_ClassificationNumber: "",
      DTU_InformationAccuracy: "",
    },
    "Model Properties": {
      "Workset (Manual)": "No",
    },
    Constraints: {
      Level: "ES_STUE",
      Host: "Level : ES_STUE",
      "Offset from Host": "0.000 mm",
      "Moves With Nearby Elements": "No",
      "Default Elevation": "0.000 mm",
    },
  },
};

for (const iterator of objPath) {
  const keySegment = iterator.split(".");
  let result = object;
  for (const prop of keySegment) {
    console.log(prop);
    result = result[prop];
    console.log(result); // The expected result is "ES_STUE"
  }
}

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

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

What causes CSS and Bootstrap elements to vanish when using a node express server?

Initially, I created a basic node server like the following: var connect = require('connect'); var serveStatic = require('serve-static'); connect().use(serveStatic(__dirname)).listen(8080, function() { console.log('Serv ...

Issue with Javascript/Jquery functionality within a PHP script

I have been attempting to incorporate a multi-select feature (view at http://jsfiddle.net/eUDRV/318/) into my PHP webpage. While I am able to display the table as desired, pressing the buttons to move elements from one side to another does not trigger any ...

Verify the channel where the bot is currently active and dispatch a message

I've been attempting to set up my bot to send a message when it joins a guild, but for some reason, it's not functioning as expected. Here is what I have tried (along with some other variations): const { PermissionsBitField } = require('dis ...

What is the method to define a function in express js that is accessible from all views?

Is there a way to develop a function within my Express JS MVC web application that can be accessed from any view? How can I define this function in middleware so it can be directly called from a view? I envision being able to use this function like: < ...

In the Opera browser, the closing script tags seem to mysteriously vanish

I recently built a website using bootstrap and implemented the JQuery load function to merge separate HTML files into one for better organization. The site is currently live on github pages. However, I've encountered an issue specifically with Opera ...

Sequence jQuery functions so that each one only runs when the previous one has finished

I want to have more control over the order of my functions in jQuery. When I click on an element, I would like an image to fade out, change its source, and then fade in the new image. The code I currently have kind of works, but it performs all these acti ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

What is the best way to loop through an object and show each item in its own row?

My goal is to loop through an object where each item has a type property. The objective is to iterate through the objects and display them in rows based on their type. Currently, it looks like this: https://i.sstatic.net/8iTtG.png I aim to have Frontend, ...

Discovering the presence of a logo within an image using NodeJS

I'm currently investigating if it's possible to process an image on a nodeJS server to determine if it contains another image. For instance: Image 1: A picture of a laptop example: http://amasoncomputers.com/wp-content/uploads/2015/04/hp-630.jp ...

Recreate body content with JQuery Mobile

I've been attempting to duplicate the entire HTML content within the tags. However, even though the appearance on screen is correct, none of the links are functioning.</p> <p>To view the fiddle, click here: [Here is a fiddle][1]</p> ...

Creating an HTML form that resembles StackOverflow's form

I am having an issue with the behavior of my form when inserting multiple tags. I want it to function like the one on this particular website where a scroll bar appears and a new line is created. Is there a way to keep everything on the same row? Check ou ...

What causes the content of my container to disappear following a setInterval div swap in Internet Explorer?

While developing a website on Chrome and Firefox, I was informed that it also needs to function properly in Internet Explorer. I managed to resolve the double padding issue in IE, but now I'm facing a new problem. The content of my "grid" disappears a ...

"Utilizing Appcelerator Titanium to fetch JSON data from a MySQL database

Is there a way to display this data in a tableviewRow and then add it to a tableview? : sendRequest.open('GET', 'http://redirect.intocept.com/read.php'); sendit.send(); sendRequest.onload = function(){ var jsonData = JSON.parse( ...

Create a router link in Vue using the command "Vue

I have a Vue application that displays videos. I am looking to automatically generate a random router link every time I click on: <router-link to="/video/this_value_to_be_random">Random video</router-link> Within the component: <vue-vide ...

Building a sub route in React Router v4 allows developers to efficiently organize and manage

Before starting, I familiarized myself with the concept of react router by visiting https://reacttraining.com/react-router/web/guides/quick-start. I have developed a simple 3-page site in react and now want to create a list that will allow me to display so ...

Error with NextJS and styled-components in the bundle file

I recently integrated styled-components into my React project. However, when I bundled the react application using rollupjs and tried to use this bundle with NextJS, I encountered an error in NextJS: ReferenceError: window is not defined Upon inspecting t ...

Combine two distinct associative arrays into a single associative array containing an array with two associative arrays using JavaScript

How can I combine two arrays into a single array that contains more complex data structures with matching values on both sides? var arr1 = [{ "id": "4", "ip_address": "127.0.0.1", "username": "superuser", "password": "$2y$08$awherOdjNPRoDHAiNBG ...

Proper method for adding elements in d3.js

I have a block of code that selects an #id and appends a svg-element into it: var graph = d3.select(elemId).append("svg") .attr('width', '100%') .attr('height', '100%') .append('g') Within th ...

Python is having difficulty parsing the JSON file from MongoDB

I am having trouble reading the test.json file from my Python script. When I try to run the code below, it throws an error: ValueError: No JSON object could be decoded from bson import ObjectId import json from pprint import pprint with open('E: ...