I'm trying to understand a JSON object that has multiple key names pointing to a single value. How can I properly interpret this in

Encountering an object with a strange key.

const obj = {
formValues: {
'TOTAL;_null_;_null_;3;_null_': "100"
'billing;_null_;_null_;1;_null_': "Y"
'billing;_null_;_null_;2;_null_': "Y"
'billing;_null_;_null_;3;_null_': "Y"
}
}

Is there a way to parse it in order to extract the value of "100" using only the keyword "TOTAL"?

obj.formValues['TOTAL'] // results in an error

Have you come across something similar? If so, can you explain why it is structured this way? (This is not how I intended to use an object, just trying to understand the reasoning behind its design)

Answer №1

I encountered an object with multiple key names for one field.

Typically, objects in JavaScript have only a single key for each property. It is not possible for a JavaScript object to have multiple keys pointing to the same property value. (Although it is feasible to create aliases for properties, this is a different concept.)

You mentioned in a comment:

I'm attempting to access a value using a single key, is there a way to parse it somehow? The key I am referring to is TOTAL.

To retrieve the value associated with the key "TOTAL," you can first identify the actual property name and then use bracket notation to access the corresponding value:

const name = Object.keys(obj.formValues).find(name => name.includes("TOTAL"));
if (name) {
    console.log(obj.formValues[name]); // "100"
}

However, if there are multiple properties containing "TOTAL" in the name, there is no guarantee of which one will be returned. (While object properties now maintain order, the ordering of properties with complex names like those in your object depends on their creation sequence, which should not be relied upon.)

Check out this live example:

const obj = {
    formValues: {
        "TOTAL;_null_;_null_;3;_null_": "100",
        "billing;_null_;_null_;1;_null_": "Y",
        "billing;_null_;_null_;2;_null_": "Y",
        "billing;_null_;_null_;3;_null_": "Y"
    }
};
const name = Object.keys(obj.formValues).find(name => name.includes("TOTAL"));
if (name) {
    console.log(obj.formValues[name]); // "100"
}

Alternatively, you can utilize Object.entries to access both the name and value simultaneously (although this involves creating temporary arrays, which modern JavaScript engines handle efficiently):

const obj = {
    formValues: {
        "TOTAL;_null_;_null_;3;_null_": "100",
        "billing;_null_;_null_;1;_null_": "Y",
        "billing;_null_;_null_;2;_null_": "Y",
        "billing;_null_;_null_;3;_null_": "Y"
    }
};
const property = Object.entries(obj.formValues).find(([name]) => name.includes("TOTAL"));
if (property) {
    const [name, value] = property;
    console.log(`Name is ${name}, value is ${value}`);
}

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

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

Incomplete header data in Angular $resource GET request

Currently, I am working with Ionic 1.3 and Angular 1.5. My goal is to retrieve some header properties from my response. The code snippet I am using looks something like this: factory('Service', function($resource, API_SETTINGS, JsonData) { re ...

What is the best way to obtain a correctly formatted string?

When I print the string in command prompt, it appears in the correct structure. "connectionstring".""."OT"."ORDERS"."SALESMAN_ID" However, when I write it to JSON, it shows up in the following format: &b ...

PHP fails to retrieve posted data from AJAX when using serializeArray()

I have been struggling with a form that is utilizing jQuery validation and AJAX to submit data to a PHP script for backend processing. The AJAX function uses serializeArray() to collect the form values, but despite my best efforts, I cannot seem to success ...

Tips for migrating an AngularJS application to Angular

My current project involves implementing a basic search function using AngularJS (link). I want to integrate this feature into an existing Angular application. To do this, I created a new Angular app and transferred the view to app.component.html. <hea ...

Utilizing Selenium Webdriver in Java to read and write JSON files

Currently, I am developing an Automation Framework and exploring alternatives to using Excel for storing test data, element locators, and page objects. A friend of mine who is also working on Automation suggested using a JSON file to store all the require ...

Filtering Gridviews with Javascript or jQuery

My current project involves using an ASP.NET GridView with multiple ListBoxes representing Departments, Categories, Faculties, and more. The data in these ListBoxes and the GridView is dynamically loaded from a MSSQL database in the codebehind. I am in ne ...

How can I use a button created with jQuery's .html() method to conceal a <div>?

I am facing an issue with implementing a simple banner that should appear in an empty element only when specific values are returned by an Ajax call. In the banner, I want to include a Bootstrap button that hides the entire div when clicked. Due to my la ...

Is it possible to access an external website by clicking on a link within a DIV element?

I have a basic website set up like this sample.php <html> <head></head> <body> <a id="myLink" href="http://sample.com">Click!</a> </body> </html> I displayed this website within a DIV-Container on a ...

Unexpected reduce output displayed by Vuex

In my Vuex store, I have two getters that calculate the itemCount and totalPrice like this: getters: { itemCount: state => state.lines.reduce((total,line)=> total + line.quantity,0), totalPrice: state => state.lines.reduce((total,line) = ...

Is it possible to run a JavaScript script from any location?

Currently, I am diving into a Javascript script and in order to run it seamlessly from any webpage I am browsing, I am thinking of adding a button to my bookmarks or using an extension. To be honest, I am clueless about the process and despite doing some ...

Is browserHistory.push ineffective in react.js?

I am currently working on a React ecommerce website. I have encountered an issue in the login component where, upon clicking the submit button on the form, the system is supposed to check if the user is authenticated using useEffect. If the user is authent ...

Merge various observables into a unified RxJS stream

It seems that I need guidance on which RxJS operator to use in order to solve the following issue: In my music application, there is a submission page (similar to a music album). To retrieve the submission data, I am using the query below: this.submissio ...

Troubleshooting MaterialUI Datatable in Reactjs: How to Fix the Refresh Issue

Currently, I am facing an issue with rendering a DataTable component. The problem is that when I click on the "Users" button, it should display a table of Users, and when I click on the "Devices" button, it should show a table of Devices. But inexplicably, ...

Is there a way to highlight today's working hours with a different color using Vue.js?

Here is the script I have created to display the working hours: const workHour = "Monday :9:00AM to 5:00PM,Thursday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM ...

develop a submission form using jquery

I am looking to create a submit action where clicking the submit button does not refresh the page. Instead, the data inputted in div1 will be sent to kanjiconverter.php and displayed in div2 using <?php echo $newkanji ?>. There are three forms on thi ...

Using Webdriver to dynamically enable or disable JavaScript popups in Firefox profiles

I am currently working on a test case that involves closing a JavaScript popup. The code functions correctly in a Windows environment, but when I try to deploy it on a CentOS based server, I encounter the following error: Element is not clickable at point ...

Assign increasing values within an array

Is there a way to efficiently update multiple values in an array by mapping through them? I want to select and change all of them simultaneously. state.formData.forEach(item => { item.EndDate = nextDayIfSelected; }); ...

Having issues with uploading a webcam picture using ajax. Occasionally the image only seems to be saved partially. Any suggestions on what I might be

Working on my web application involves taking customer photos and uploading them with Ajax. I base64 encode the pictures, resulting in large data sizes (around 1.4MB). The process involves Ajax calling a php script to handle the data transfer and saving it ...

Ending a session in Node.js with Express and Socket.io

I've been grappling with this issue for a few days now and I'm just not able to wrap my head around it. I need to end my session when I navigate away from the webpage, but the error message I keep receiving (which ultimately crashes the server) r ...