Is it possible to restrict the number of entries in a JavaScript object to just two

I have a task in my JavaScript class where I need to create a script to generate an object. The issue I am facing is that I want to restrict the possible values of a property in my object. Below is the code snippet:

var StudentObject = new Object();
var StudentStatus = new Object();
StudentStatus ={
   paid:true,
   registrationOK:true
}
StudentObject = {
   status: StudentStatus,
   track: "",
   course:"Applied Informatics"
} 

In the "StudentObject" object, there is a property called "track". I want to limit its value to either "MBT" or "PBT". Is there a simple way to achieve this?

Appreciate your help.

Answer №1

It is not possible to limit the values that a public object property in javascript can hold based on how it is currently defined.

One alternative approach would be to use accessor methods for setting and retrieving the value, which could enforce constraints on what values are allowed. By storing the data within a closure that is inaccessible from outside the object, only the accessor methods would have access to it. For more information on implementing private instance variables with accessors, you can refer to .

function StudentObject(studentStatus, program) {
   // Private instance variable, only accessible internally
   var track = "";

   // Public methods
   this.setTrack = function(value) {
       if (value === "MBT" || value === "PBT") {
           track = value;
       }
   }

   this.getTrack = function() {
       return track;
   }

   this.status = studentStatus;
   this.program = program;
}

var studentStatus = {
    paid: true,
    enrollmentOK: true
}

var student = new StudentObject(studentStatus, "Applied Informatics");
student.setTrack("PBT");
alert(student.getTrack());    // "PBT"
student.setTrack("xxx");
alert(student.getTrack());    // "PBT"

Answer №2

You could potentially try this approach:

function handleTraject(x) {
    if (x === 'MBT' || x === 'PBT') {
        return x;
    } else {
        return null;
    }
}

Answer №3

This might be a bit challenging :(

You may want to reference set as well as new and Object.defineProperty

Sample Code:

function StudentInfo() {
    var _course = undefined;

    Object.defineProperties(this, {
        course: {
            enumerable: true,
            configurable: true,
            get: function () {
                return _course;
            },
            set: function (value) {
                if ((typeof(value) === "string") && (value.indexOf("Math") >= 0 || value.indexOf("Science") >= 0)) {
                    _course = value;
                }
            }
        }
    });
}

var student = new StudentInfo();
student.course = "history"; // course will not be set to history
console.log(student.course); // undefined
student.course = "mathematics"; // course will be set
console.log(student.course); // mathematics

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

To manipulate the array in a more complex manner, either add or remove the item based on its existence: if it's already in the array, remove it; if it

As I prepare to send key-value pairs to the backend in the form of a JSON structure, each representing a category (e.g., customer churn rate), I encounter an issue. The idea is to add checkmarked options to the array of their respective categories. However ...

Using regex to confirm prices are accurate

Can anyone assist me with validating input using regEx in Vue? I'm struggling to create one and haven't been able to find the correct pattern online for what I need. The specific validation I am attempting is for a price value that should be a f ...

Executing API POST requests by iterating over an array in ECMAScript 6

My dilemma lies in processing an input that follows the format of "ABC, DEF, GHI, ...." The task at hand is to convert this comma-separated list into an array and make a POST request for each value in the array using my API. I'm seeking guidance on t ...

What is the significance of the term "Object object"?

I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick) is clicked. There are [Object object] elements in the array. The last line ...

Execute a sorted operation with proper authorization

Recently, I developed a NextJs dashboard that enables Discord users to connect to their accounts. One of the main features is retrieving the user's guilds and filtering them to include only the ones where the user has either the MANAGE_GUILD permissio ...

Execute the JavaScript `execCommand("ForeColor")` command to remove the highlighting

Is there a way in JavaScript to dynamically remove text highlights that were applied using the execCommand("HiliteColor") method? I want to check if the selected text is within a highlighted span and then remove the highlight. Additionally, how can I handl ...

AngularJS not swapping the data-url with the scope URL provided in {{ uploadUrl }}

Currently, I am utilizing jQuery fileupload to send a file to a specific URL. Within my controller, the code snippet below demonstrates how I generate the URL for uploading: uploadService.getUploadURL($scope.projectId).then(function (url) { $scope.up ...

Arranging Data in MeteorJS

I recently delved into MeteorJS, Mongodb, and Iron:router, and wrote a small code to sort a list of websites based on user interactions. Initially, everything worked smoothly, but I encountered an issue with sorting near the end. Specifically, the websit ...

Using JSON to dynamically generate pages in Gatsby programatically

Currently, I am utilizing Gatsby to dynamically generate pages, and I am looking to do so at two distinct paths: covers/{json.name}.js and styles/{json.name}.js. While I have successfully set this up using the gatsby-node.js file, I would like to transit ...

Add distinctive formatting for the final element that is not the last child

Presented with a fascinating challenge, I find myself with an ever-changing number of .child.red children. I am in need of referencing the last .child.red element dynamically using styles. Although I have attempted to achieve this on my own, I am curious a ...

Use JavaScript to change the CSS pseudo-class from :hover to :active for touch devices

Looking to eliminate hover effects on touch devices? While it's recommended to use a hover class for hover effects, instead of the hover pseudo-class, for easier removal later on, it can be a challenge if your site is already coded. However, there&apo ...

Converting JSON into key-value pairs using ReactJS

Here is a JSON object that I have: [ { "crime": "LARCENY-NON_VEHICLE", "count": "23217" }, { "crime": "AUTO_THEFT", "count": "13675" ...

Activate vertical scrolling in JavaScript when an image is clicked

I currently have a collection of button images with different hover effects specified like this: <img src="home.PNG" onmouseover="this.src='homemo.PNG'" onmouseout="this.src='home.PNG'" /> My goal is to make them scroll down to ...

Vue is alerting me that I cannot assign a reactive property to an undefined, null, or primitive value, specifically null

When retrieving data from Firebase, I am attempting to update the properties of the object being displayed on the UI. However, whenever I try to make any changes to the data, an error is thrown. Error in v-on handler: "TypeError: Cannot use 'in&apos ...

Tips for saving a web page using Selenium Webdriver in JavaScript

Is there a way to programmatically save an entire webpage using Selenium Webdriver JS in Firefox? I have been able to bring up the Save As dialog with the following code: driver.findElement(webdriver.By.tagName('html')).sendKeys(Key.CONTROL + &ap ...

Updating HTML content with Node JS using MYSQL data

Seeking Guidance on Updating HTML Data Using Node.js I am looking for a way to update the HTML data in my files using Node.js without the use of EJS or any view engine. My views folder contains .js files that return HTML, and I need to change the data fro ...

Is it possible to bulk update a sorted set using the Redis client in Node.js?

Looking to update multiple records in a sorted set using Redis client in Node.js. Currently, I am able to update a single record with client.zAdd(key,{score:score, value:memberId}). Is there a command or function that allows for bulk updates in Redis? I se ...

Error encountered while attempting to extract JSON dictionary in Python

I am currently experimenting with a Python project designed for interacting with my Lego SBrick, which I found on this GitHub repository. After establishing a connection with the SBrick, I used the following code snippet: json_response = client.rr_get_ad ...

Ways to update the select field without having to reload the entire page

I am working on a unique feature that involves two levels of drop down menus. When a user makes a selection in the first level, a corresponding set of options will appear in the second level. For example, I have 6 options in the first level, each with its ...

Tips for triggering animation only when the element is in the viewport

I'm currently developing in React and facing a challenge where I need to trigger a fade animation for an element only when it becomes visible on the screen. The issue is that right now, the animation plays as soon as the page loads, which defeats the ...