Transform nested entities into a single entity where any properties that are objects inherit from their parent as prototypes

Exploring a new concept. Consider an object like:

T = {
  a: 2,
  b: 9,
  c: {
    a: 3,
    d: 6,
    e: {
      f: 12
    }
  }
}

The goal is to modify it so that every value that is an object becomes the same object, with the parent object as prototype.

For example, we should get the following results:

> T.c.b
9
> T.c.e.b
9
> T.c.e.a
3
> T.c.c.c
{a: 3, d: 6, e:[Object]}

A set of functions has been developed already, which are almost working as intended:

function chainer(object) {
    for (const key in object) {
        if (object[key] !== null && typeof (object[key]) === 'object') {
            let Constructor = function () {
            };
            Constructor.prototype = object;
            let objectValue = {...object[key]};
            object[key] = new Constructor();
            for (const savedKey in objectValue) {
                object[key][savedKey] = objectValue[savedKey];
            }
        }
    }
}

function chain(object) {
    chainer(object);
    for (const key in object) {
        if (object[key] !== null && typeof (object[key]) === 'object') {
            chainer(object[key]);
        }
    }
}

While the above example works fine, there seems to be an issue when trying the following:

T = {a:4, g:{g:{g:{g:{g:{g:{g:{}}}}}}}

This yields unexpected results:

> T.a
4
> T.g.a
4
> T.g.g.a
4
> T.g.g.g.a
undefined
> T.g.g.g.g.a
undefined

It is puzzling why it stops working at a certain point; could there be some unknown limitation causing this?

Feeling a bit stuck and running out of ideas, any suggestions?

Answer №1

This code snippet appears to be functioning correctly:

ouroboros = (x, parent = null) => {
    if (!x || typeof x !== 'object')
        return x;
    let r = Object.create(parent);
    Object.entries(x).forEach(([k, v]) => r[k] = ouroboros(v, r));
    return r;
};

//


T = ouroboros({x: 4, a: {b: {c: {d: {e: {}}}}}});
console.log(T.a.b.c.a.b.c.a.b.c.a.b.c.a.b.c.x);

Alternatively, objects can be mutated rather than copied using the following approach:

ouroboros = (x, parent = null) => {
    if (x && typeof x === 'object') {
        Object.setPrototypeOf(x, parent);
        Object.values(x).forEach(v => ouroboros(v, x));
    }
};

Answer №2

It seems that the approach you were looking for is something along these lines:

recursionFunction = function (obj) {
  return Object.keys(obj).reduce((accumulator, key) => {

    if (typeof accumulator[key] === "object") { 
        const keyValue = {...recursionFunction(accumulator[key]), ...obj}
        return {...accumulator, ...keyValue, get [key]() { return this}} 
    }
    return accumulator;
  }, obj)
}

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

Retrieve information from a JavaScript file to incorporate into an HTML file

Seeking a solution to store the base URL in a separate JavaScript file, I've implemented a JavaScript file named config.js containing: export const baseUrl = "https://example.com/"; There are multiple HTML files utilizing this base URL for ...

Error: The component passed is invalid and cannot be defined within kendo UI

Check out this example https://www.telerik.com/kendo-vue-ui/components/grid/ showcasing a computed method gridSearchMessage() { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all colu ...

What is the best way to add or delete data when specific radio buttons are chosen?

Hey there, I'm facing an issue where the data is being appended regardless of which radio button is selected. Can someone help me with a solution on how to properly add and remove data based on the selected radio button? $( document ).ready(functio ...

What methods are commonly used to calculate the bitsPerSecond rate for media recording?

Is there a specific formula that combines frames per second and resolution to determine the bits per second for video encoding? I'm struggling to figure out the appropriate values to use for specifying the bits per second for 720p, 1080p, and 4k video ...

Techniques for slowing down the propagation of events with jQuery

Is there a way to show a note after a user submits a form but before they leave the page? Here is an example of what I'm currently using: $('form').submit(function(event) { $('.note').show(); setTimeout(function() { ...

Encountering a problem with controlling the number of splits allowed

I am encountering an issue with splitting my string using the code below. splitter.map((item1) => { let splitter1 = item1.split("=")[0].trimLeft(); let splitter2 = item1.split("=")[1].trimRight(); }); The content of item1 is as fo ...

React Sentry Error: Attempting to access properties of undefined object (reading 'componentStack')

Utilizing the ErrorBoundry component from Sentry in my react project has been a goal of mine. I aim to confine the errors reported to Sentry specifically for my React app, as it is deployed on multiple websites and I want to avoid picking up every JS error ...

Sending data using jQuery to a web API

One thing on my mind: 1. Is it necessary for the names to match when transmitting data from client to my webapi controller? In case my model is structured like this: public class Donation { public string DonorType { get; set; } //etc } But the f ...

As the background image shifts, it gradually grows in size

I'm attempting to create an interesting visual effect where a background image moves horizontally and loops seamlessly, creating the illusion of an infinite loop of images. Using only HTML and CSS, I've run into an issue where the background ima ...

Tips for retrieving the value of a tag within a modal popup

I am trying to extract the value from an 'a' tag using the code below. <div class="modal fade show" id="myModal" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" style="display: block;"> <div class="modal-d ...

Animation of two divs stacked on top of each other

I am trying to replicate the animation seen on this website . I have two divs stacked on top of each other and I've written the following jQuery code: $('div.unternehmen-ahover').hover( function () { $('div.unternehmen-ahover' ...

Accessing Elasticsearch from Kibana without the need for authentication and sending requests freely

Currently, I am in the process of developing a plugin for Kibana with the intention of establishing communication with Elasticsearch, utilizing Shield for security measures. Thus far, my approach has involved sending requests through the server with code ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...

What is the best way to view and use the data stored within this JSON object?

Obtaining information from a straightforward API (). I retrieve the data using getJSON: var police = $.getJSON(queryurl); A console.log on police displays this: However, I am unable to access the properties within the object. I assumed that I could ac ...

Try fetching new data with React Query by refetching

Whenever a button is clicked, I attempt to fetch new data by calling Refetch. const {refetch,data,isLoading} = useQuery( "getkurs",() =>fetch( `https://free.currconv.com/api/v7/convert? q=${selected.country.currencyId}_IDR&compa ...

Ways to retrieve directory information in Next.js hosted on Netlify

Having trouble retrieving a list of directories in Next.js on Netlify. The code works fine on localhost, but once deployed to Netlify, an error is triggered: { "errorType": "Runtime.UnhandledPromiseRejection", "errorMessage": ...

How to retrieve the button value in HTML

One of the HTML components I am working with is a button that looks like this: <button>Add to cart</button> My goal is to retrieve the text within the button, which in this case is "Add to cart." To achieve this, I need to extract this value ...

Action creator incomplete when route changes

In my React-Redux application, there is an action creator that needs to make 4 server calls. The first three calls are asynchronous and the fourth call depends on the response of the third call. However, if a user changes the route before the response of t ...

I'm having an issue with my NextJS timer where it doesn't stop and ends up going into negative numbers. Any

Here is the code snippet for my timer component. It fetches the 'createdAt' prop from the database and functions correctly. However, I have encountered an issue where the timer does not stop at 0 but continues running indefinitely. I attempted to ...