What is the best way to retrieve a default property from a JavaScript literal object?

In the following example, a JS object is created:

var obj = {
      key1 : {on:'value1', off:'value2'},
      key2 : {on:'value3', off:'value4'}
}

Is there a clever method to automatically retrieve the default value of the key1 on property when only obj.key1 is passed without specifying a property?

var key1State = obj.key1; // I want 'value1' to be returned here instead of obj.key1{...}

Is it feasible to somehow determine within the body of the object definition which property (if any) is being requested when calling the object?

Answer №1

Perhaps this solution could be what you are searching for - by tinkering with the valueOf or toString methods.

Consider the following scenario:

let object = {
      property1 : {on:'data1', off:'data2', toString : function(){ return this.on; }},
      property2 : {on:'data3', off:'data4', toString : function(){ return this.on; }}
}

let stateOfProperty1 = object.property1; // returns the object
let stringStateOfProperty1 = '' + object.property1; // outputs "data1"
object.property1 == "data1"  // evaluates to true
object.property1.toString() === "data1"  // also true

Thus, in cases where using the default value as a string is necessary, this method could prove beneficial.

Answer №2

Although this solution may not directly address your issue, it could still prove to be helpful.

Consider utilizing getters in your code.

var data = {

  fruit : {ripe:'apple', unripe:'banana'},
  vegetable: {ripe:'tomato', unripe:'cucumber'}, 
  get selectedFood () { return this.fruit.ripe }

}

By implementing getters like this, you can easily access the desired values from your objects.

Answer №3

I understand your concept, but I believe the more efficient approach would be to utilize a function such as getState to retrieve the current state of the object.

var obj = {
  key1: {on:'value1', off:'value2'},
  key2: {on:'value3', off:'value4'}
};

var key1State = getState(obj.key1);
var key2State = getState(obj.key2.off);

function getState(obj) {
  return obj.on || obj;
}

console.log(key1State, key2State);

View codepen example.

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

Do not attempt to log after tests have finished. Could it be that you overlooked waiting for an asynchronous task in your test?

Currently, I am utilizing jest in conjunction with the Vue framework to create unit tests. My test example is successfully passing, however, I am encountering an issue with logging the request. How can I resolve this error? Is there a mistake in my usage o ...

Trouble with loading scripts after transitioning to a new page with AJAX (Barba.js)

Exploring the potential of using AJAX for smooth page transitions. Tried two different methods so far: manually coded transition from () and Barba.js approach (). With both methods, scripts work on initial load but fail to execute when navigating to anot ...

The $.inArray() function returns a value of false or -1, despite the fact that the variable

My goal is to verify that my currentMedia variable (which exists in the DOM) can be located within my array media, and then return the index i, which should be 0 instead of -1. When I execute console.log(media[0]); and console.log(currentMedia);, the outc ...

Server side processes automatically converting boolean parameters in Axios get requests to strings

My code involves a JSON object being passed as parameters to the Axios GET API. Here is the JSON object: obj = { name: "device" value: true, } The Axios GET request is made with the above object like this - tableFilter = (obj) => { ...

What is the best method for retrieving environment variables within a React JS web application?

Within my render method, I am trying to access a specific environment variable. However, because it is a custom ENV variable, I cannot utilize (process.env.NODE_ENV). According to this source, React filters all process.env access. What would be the best w ...

Execute JavaScript code following the completion of loading and running an external script

My goal is to dynamically load and run a third-party JavaScript file (from a different domain) and then execute some of my own code afterwards. One option I'm considering is using jQuery's $.getScript: $.getScript('https://login.persona.org ...

Reverting Changes Made with JQuery Append

I have a table where each cell contains a button. When the button is pressed, it adds text to the cell. I am looking for a way to remove this text from the cell when the same button is pressed again. It's important to note that this button appears mul ...

Initiate a button click event from the parent element situated within an Iframe

I am facing a challenge in accessing a button within an iframe. The path to the button is as follows: div.iframe-container > iframe#builder-frame > html > body > div#header > ul.header-toolbar.hide > li > span.deploy-button-group.butt ...

Problem with Java class in GWT JsInterop

Having some trouble with JsInterop while wrapping up a piece of JavaScript code. The JavaScript code looks like this: com = { gwidgets: {} }; com.gwidgets.Spring = function () { this.name = "hello"; }; com.gwidgets.Spring.prototype.getName = ...

Tips for accessing image data generated by the Bootstrap File Input plugin

I have a div that utilizes the Bootstrap File Input plugin to select, show, change, and cancel images. The image data is generated dynamically by the plugin. <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinpu ...

Testing React JSX components using ES6 unit tests

Currently, I am utilizing React, JSX, ES6, and Karma. I am facing an issue with my code. Can anyone pinpoint what might be wrong? I am attempting to execute a test using Karma-Runner but encountering some obstacles: let React = require("react") ...

Add AngularJS to an AJAX call when the user clicks on it

I'm currently exploring the SoundCloud API and looking to implement a feature where users can add a song to the page by clicking on it from the search results. I've decided to utilize Plangular, which you can find more information about here. How ...

Looking to extract data from various checkbox options and save it as an array variable

For a coding boot camp assignment, I'm working on a modal that includes options for the days of the week. My approach involves using Jquery .each and CSS :checked to retrieve the values assigned to each input. However, every time I attempt to log the ...

Streamline retrieval of alphanumeric indexing within json

When accessing json data using jquery, I came across an index structure like this: data.rows[0].student_1 data.rows[0].student_2 data.rows[0].student_3 and so on... Now, I'm looking to automate this process by creating a loop that allows me to acces ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

Effortlessly find data in an HTML table and showcase the results instantly without

I am looking for a way to implement search functionality in my table without refreshing the page. The fields above the table are used for searching and I want the results to be displayed within the same table. Here is an example of the code: <?php $for ...

switch out asterisk on innerhtml using javascript

Is there a way to replace the asterisks with a blank ("") in the innerHTML using JavaScript? I've attempted this method: document.getElementById("lab").innerHTML = document.getElementById("lab").innerHTML.replace(/&#42;/g, ''); I also ...

What is the process for transforming pagination numbers into Arabic numerals?

When working with pagination in my project, I have utilized both ant design and material ui. However, I encountered a problem when attempting to change the default Latin numbers to Arabic numbers. Despite trying ant design localization, I was unable to aff ...

Unable to retrieve information from the wiki API

Here is the link to my codepen project: https://codepen.io/mlestina/pen/OZpOQW?editors=1111 I am having trouble retrieving data from the Wiki API. When I check the Contr-Shift-J readout, I see: Loading failed for the <script> with source “https: ...