Create a string representing the path to access a property within a nested object

I am dealing with an object that has nested properties:

{ 
    x: { 
        y: { 
            z: { min: 1, max: 2 },
            w: 5 
        }
    }
}

The levels of nesting can vary. It can end with an object containing properties like 'min', 'max', or 'in', or it can simply be a non-object like a string, number, or boolean value.

My goal is to create a string representing the path to those endpoints.

For example, if we take the above object, I would want the resulting string to be as follows:

objPaths(x)

=> {
     "x.y.z": { min: 1, max: 2 }
     "x.y.w": 5
   }

Answer №1

To handle this scenario, you can implement a recursive function that utilizes a for...in loop. In addition, if the current property's value is an object, you should verify if any of its keys are min or max before proceeding to the next level.

const obj = {"a":{"b":{"c":{"min":1,"max":2},"d":1}}}

const objPaths = (obj, paths = {}, prev = '') => {
  for (let key in obj) {
    let str = (prev ? prev + '.' : '') + key;
    if (typeof obj[key] != 'object') paths[str] = obj[key];
    else if (Object.keys(obj[key]).some(k => ['min', 'max'].includes(k))) paths[str] = obj[key];
    else objPaths(obj[key], paths, str)
  }
  return paths
}

const result = objPaths(obj);
console.log(result)

Answer №2

One way to approach this problem is by combining iterative and recursive methods. First, check if the object contains keys for 'min' or 'max'. If not, iterate through the object to find the desired value.

function explorePath(obj) {
    function search(o, path) {
        if (o && typeof o === 'object' && !['min', 'max'].some(key => key in o)) {
            Object.entries(o).forEach(([key, value]) => search(value, path + (path && '.') + key));
            return;
        }
        outcome[path] = o;
    }

    var outcome = {};
    search(obj, '');
    return outcome;
}

console.log(explorePath({ a: { b: { c: { min: 1, max: 2 }, d: 1 } } }));

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

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...

JavaScript FF IE Update + problem with messaging script

I am currently using an ajax_update script that updates file.php every 60 seconds. The output of file.php after updating a table is as follows: <div id='message' style="display: none;"> <span>Hey, <b><? echo $userid; ?&g ...

Determine the presence of an HTML data attribute within any of the parent elements

I am attempting to locate an HTML data attribute on one of the ancestors of a given element, baseElement, and retrieve its value if found. In the case where the attribute is present in multiple ancestors, I am interested in the one closest to baseElement. ...

Ways to retrieve an isolated scope in a directive without utilizing a template

It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope. However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I woul ...

Steps for constructing an object containing an array of nested objects

I've been working on this problem for some time now, and it's starting to feel like a messy situation that just won't come together. I'm trying to recreate an object with 5 properties and a nested array of objects, but so far, it's ...

Setting the focus on an input when updating a property in the Pinia store using Vue

When a component I have is clicked, it triggers a function in the store: <button @click="this.store.foo()"></button> Within the store, I am updating a specific property: state: () => ({ focusIn: false, }), actions: { foo() { ...

JavaScript - Loading image from local file on Linux machine

I have a server running and serving an HTML page, but I am trying to display an image from a local drive on a Linux machine. I've tried using file://.., but it doesn't seem to be working for me on Ubuntu 18.04. There are no errors, the img tag ju ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Transferring data between two HTML files through the POST method

Is there a way to pass two values (parameters) from one HTML page to another without displaying them in the URL, similar to using the POST method? How can I retrieve these values on the second HTML page using JavaScript, AJAX, or jQuery? For example: cli ...

Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Javascript's ReferenceError occasionally acts inconsistently when using Firefox's scratchpad

While delving into the world of Javascript for learning purposes, I encountered an unexpected behavior. Let's explore this scenario: function hello(name) { let greet = 'Hello ' alert(greet + name) } hello('world') alert(gree ...

Is it possible to set an onmousedown event to represent the value stored at a specific index in an array, rather than the entire array call?

Apologies if the question title is a bit unclear, but I'm struggling to articulate my issue. The challenge lies in this synchronous ajax call I have (designed to retrieve json file contents). $.ajax({ url: "/JsonControl/Events.json", dataTyp ...

Enhance your date with a specific month using MomentJS

I attempted to retrieve only the Saturdays of upcoming months with: var momentDt = moment('2017-03-18').add(1); //or 2 or 3 However, adding 1 results in April 18, 2017, which is a Tuesday. Is there an easier way in moment to achieve this wit ...

What is the best way to retrieve information from a database when parameters need to be included in the URL?

Currently, I am working on React and seeking some assistance. Below is the structure of a table I am dealing with: Your teaching classes: IDSubject ClassSchool Year 1MathematicsV2019 View 2MathematicsVI2019 View 3MathematicsVII2019 ...

The replaceWith() function in jQuery is able to transform PHP code into an HTML comment

How can I change a div element in a click event handler, while ensuring that PHP code inside the element remains intact and does not get moved into an HTML comment? You can find my code snippet below: $("#replaceCat1").click(function(){ $("div.boxconte ...

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

Introduction to Angular controller binding for beginners

I'm currently going through this tutorial : http://www.youtube.com/watch?v=i9MHigUZKEM At 46:32 minutes into the tutorial, this is the code I have implemented so far : <html data-ng-app="demoApp"> <body data-ng-controller="SimpleControlle ...

Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is th ...