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

How can I pass an Objective-C object to JavaScript?

Currently, I am working on a UIWebView project that involves HTML and JavaScript. One of my friends is working on something similar but for Android. The challenge I'm facing is that in Android, there is a simple way to send an Android object to JavaS ...

Testing the JSONObject Unit Always Returns Null

After staring at this code for what feels like an eternity, I still can't pinpoint the issue. JSONObject jsonResponse = new JSONObject(); jsonResponse.put("JSON", "hi"); String myString = jsonResponse.getString("JSON"); assertEquals("hi", myString); ...

How can I convert a list of checkboxes, generated by ng-repeat, into multiple columns?

Here is the HTML code snippet: <div class="checkbox"> <label> <input type="checkbox" ng-model="selectedAll.value" ng-click="checkAll()" />Check All </label> </div> <div class="checkbox" ng-repeat="carType i ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

The URI entered is not valid: The parsing of the hostname failed. Electron Builder

Having an issue while trying to build an electron app using squirrel, even though the iconUrl is valid. Here is my package.json configuration: "squirrelWindows": { "iconUrl": "http://95.85.39.111:5005/skylog.ico" }, Error message received: An unhand ...

Is there an error when iterating through each table row and extracting the values in the rows?

Here is a basic table that I am attempting to iterate through in order to retrieve the value of each cell in every row where there are <td>s present. However, I encounter an error indicating that find does not exist despite having added jQuery. Any ...

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...

What could be causing the data-title attribute to not update in AngularJS?

When utilizing AngularJS and Bootstrap's popover, I have successfully bound to data-content, but am encountering issues with binding to data-title: <li data-trigger="hover" data-placement="bottom" data-title="{{'Memory limit' | l10n}}" d ...

Executing multiple HTTP requests simultaneously in groups using an asynchronous for loop for each individual request

I'm currently working on running multiple requests simultaneously in batches to an API using an array of keywords. Read Denis Fatkhudinov's article for more insights. The issue I'm facing involves rerunning the request for each keyword with ...

Do AngularJS applications function similarly to windows?

Do AngularJS apps behave like windows? And is it possible to add an event listener to them? I am currently working on a proof of concept to see if an Angular app can communicate with a server without impacting the host. One potential solution I have thou ...

"Easily toggle the visibility of values in checkboxes and organize them into groups with the power of JavaScript

Hey there! I am currently working on a project that involves grouping checkboxes and hiding/unhiding their content based on user interaction. Essentially, when the page first loads, the "All CARS" checkbox will be checked by default. If I then check the "C ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

Activate modifications in a distinct column?

I've been exploring a solution to achieve a similar functionality where clicking or hovering on headings in a column brings up corresponding text in another column. My idea is to use list items with a carousel for this purpose, but I'm facing so ...

What is the best way to extract a single String element from a List<MyList> Array list?

I have been working on implementing a RecyclerView where I retrieve data from an API in JSON format. To achieve this, I created two models - one for my RecyclerView data and the other for my calendar view. The data retrieval for the RecyclerView using a cu ...

Is it possible to create a custom options array in React-Select?

I've been working with react-select using the package from . The required format for the options prop is {value:something, label:something}. I have a list of objects with additional key-value pairs and I'm wondering if there's a way to avoi ...

Update the identification of a second object in the realm

Receiving a list of business data in JSON format from an API is crucial for my app. Since this list is dynamic and can change frequently, I have to fetch it periodically to ensure the data is updated. Every business entry includes an address, but unfortuna ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Managing a JSON dictionary to a text file: Tips and tricks

I am working with a sample.json file that contains code in the C language dataset, represented as a dictionary. { "0_0": "int curl_mvsprintf ( char * buffer , const char * format , va_list ap_save ) {\n int retcode ;\n retcode = ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Is it possible to utilize setIn for establishing a fresh index on an array that is currently empty?

Having trouble using Immutable in this specific structure: myMap = Map({a: [], b: []}); myMap.setIn(['a', 0], 'v'); An exception is being thrown when trying to do this immutable.js Error: invalid keyPath at invariant (immutable. ...