Ways to Ensure a Property of an Object Remains Synced with Another

I'm dealing with the following Object structure:

{
   a: "123"
   b: "$a"
}

In this setup, b should always be equal to the value of a.

Any suggestions on how I can achieve this using JavaScript?

Answer №1

If you want to access the property b using a special method, you can utilize a getter within an object.

var obj = {
    a: "123",
    get b() {
        return this.a;
    }
};

console.log(obj.b);

Another option is to explore an ES6 feature called Proxy.

The Proxy object allows for custom handling of fundamental operations (e.g., property lookup, assignment, function invocation, etc).

In this case, you can grab the prop, check if it contains a $, and return the value associated with that property.

var obj = { a: "123", b: "$a" },
    p = new Proxy(obj, {
        get: function(target, prop) {
            return target[prop][0] === '$' ? target[target[prop].slice(1)] : target[prop];
        }
    });

console.log(p.b);

Answer №2

To create a genuine JavaScript object, you can achieve this by using a getter and setter with the help of Object.defineProperty().

Answer №3

You have the option to establish a "class"


var person = new function()
{
this.name = "John",
this.age = 30
}

console.log(person.name)

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

Tips for utilizing the .clone() method within a loop or for each individual element of an array

Due to certain requirements, I find myself in a situation where I need to customize the invoice template within the software I use. The invoices are generated in HTML format, prompting me to consider utilizing Stylish and Grease Monkey for this task since ...

Dispatch an angular POST Request

I am facing an issue where Angular is sending a GET request instead of a POST request when I want to send a post request. The code for my Angular request is as follows: $http({ method: 'POST', url: pages_url, params: { ...

Using ng-mouseover along with ng-if and an animated class causes issues

Whenever I hover over a link, it triggers a change in a variable value which then displays a <p> tag using ng-if. The code snippet looks like this: <div class="position text-center" ng-mouseover="social=1" ng-mouseleave="social=-1"> &l ...

What is the best method for embedding JSON data into a script tag within a Zope Chameleon template?

Creating a pyramid/python application where the view callable passes in an array variable called data, structured as [[[x1,y1,z1,],...],[[v1,v2,v3],...]] In the view callable: import json jsdata = json.dumps(data) I aim to place this data within a java ...

Filter a div based on multiple conditions using JavaScript/jQuery

In my filtering system, I have two sections: place and attraction. When I select a place, the corresponding div is displayed according to the selected place. Similarly, when I select an attraction, only the attractions are filtered accordingly. <ul clas ...

The ReactJS input box is stubbornly rejecting all input

Struggling with this code and can't seem to figure out why the input lines aren't accepting anything. After searching extensively, I decided it was time to ask for help. P.S. I am new to react class App extends React.Component { state = { inp ...

The date range picker displays the previous arrow but not the next arrow

I am currently using the DateRangePicker tool and for some reason, I am not seeing the arrow that should appear on the right side. I have double-checked my configuration but can't seem to figure out what is causing this issue. In the image attached, ...

Leverage the Express JS .all() function to identify the specific HTTP method that was utilized

My next task involves creating an endpoint at /api that will blindly proxy requests and responses to a legacy RESTful API system built in Ruby and hosted on a different domain. This is just a temporary step to transition smoothly, so it needs to work seam ...

When incorporating Vue as an npm package, a Vue 3 app may inadvertently clear the mounted element upon initialization

I have a straightforward Vue 3 application that is working perfectly fine when I include Vue as a script, as shown in the code snippet below. However, I need to integrate it with webpack by including it as an npm package. When I do this, the app loads but ...

Having trouble loading a JSON object into a Datatable using Jquery?

I am currently utilizing DataTables in combination with Jquery. I have a data source in the form of an JSON object that I intend to retrieve via Ajax and showcase within the table. The JSON data is retrieved from the /live/log url and has the following fo ...

Using the react-router Navigate component within a Next.js application allows for seamless

Is there a way to achieve the same result as the Navigate component in react-router within Nextjs? The next/Router option is available, but I am looking for a way to navigate by returning a component instead. I need to redirect the page without using rout ...

How can I retrieve the span html element without using a class with ajax?

Trying to work with Ajax syntax for the first time, I have this HTML code. <div class="select2-container select2" id="s2id_ServiceID-2-1" style="width: 100%;"> <a href="javascript:void(0)" onclick="return false;" class="select2-choice" tabind ...

Issue with Ionic 4 button not triggering event when created using Jquery

Utilizing Ionic 4 in my current project, I have integrated it with Jquery. On the HTML page, a button is created using the following code: <ion-button (click)="event1()">EVENT1 </ion-button> In the .ts file for the page, a function is impleme ...

Unleashing the y-axis and enabling infinite rotation in Three.js

In my three.js project, I am utilizing orbital controls. By default, the controls only allow rotation of 180 degrees along the y-axis. However, I would like to unlock this restriction so that I can rotate my camera infinitely along the y-axis. As someone ...

What is the reason for the addEventListener function not being able to access global variables?

I have set up an event listener function to utilize popcorn.js for displaying subtitles. Additionally, I have created functions that are unrelated to popcorn.js outside of the event listener and declared a global variable array. However, when attempting ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

ReactJS Scripts are throwing an error indicating that the function require is not defined

Just starting out with React and I discovered that we can integrate React by adding the necessary scripts to our main index.html file. I followed all the steps to include the script and even made sure to add Babel since I'm writing my main App in JSX. ...

"Encountering a 404 error in a JQuery Ajax POST request when trying to send

Recently, I have been working with Adobe InDesign extensions and one of the tasks involves uploading an XML file to a server using a jQuery AJAX POST call. To achieve this, I need to read the XML file from the file system, store it in a variable, and then ...

Position div elements randomly on the webpage when it first loads

I am trying to achieve a set of divs that will appear randomly on the page when it loads. Currently, I have the divs moving around the viewport in a random manner, but they all seem to load in the top left corner. This is the method I am currently using: ...

Encountering a TypeError in semantic-ui-react Menu: instance.render function not found

As a React novice, I have been working on a project that involves React for some time. However, I had not yet delved into dealing with packages and dependencies. It seems like my current issue is related to this. The problem emerged in a project where I w ...