Manipulate a JSON object with JavaScript

Struggling to find a solution on my own.

In my hidden field, I have some JSON data stored.

To retrieve this data, I'm using the following syntax:

 $(document).ready(function() {
var data = $("#result").text();
var j = JSON.parse(data);
j.my_item.total_price==="2222";
console.log(j.my_item.total_price);

});

Although the variable 'j' displays the correct information, I'm unsure how to update the total_price value.

Any suggestions on how to go about updating the total_price?

Answer №1

To set a value to an object property, you can use the following methods:

obj.my_property = "value";

Alternatively, you can also use array-like syntax:

obj['my_property'] = "value";

You can also mix and match these methods:

obj.my_property['sub_property'] = "value";
obj['my_property'].sub_property = "value";

Answer №2

$(document).ready(function() {
var info = $("#result").text();
var k = JSON.parse(info);
k.my_item.price="2222";
console.log(k.my_item.total_price);

});

=== isn't just an assignment operator, it's a type-strict comparison operator.

Learn more about it here:

Difference between == and === in JavaScript

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

The data fetched from the API is not appearing in the FlatList component on the screen, even though it is successfully logged in the console. What could be causing this issue?

After successfully fetching data from an API in my React Native app and logging it to the console, I encountered an issue where the data is not showing up in the FlatList component. const HealthLinkMain = () => { const [data, setData] = useState([ ...

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

What is the best way to deserialize certain fields from a Json object using Gson?

Here is the JSON string I have: [ { "channel": "/bvmt/initValues", "data": { "value": { "instrumentIds": "['TN0007250012','TN0007500010']", "instruments": "[{'mnemonic':'ADWYA',&apos ...

Utilizing JavaScript to display numerous variables within a text box

After creating an HTML form, I encountered an issue where only one selected item was displayed in the text field. Can anyone help me solve this problem so that multiple names can be printed in the textfield? function myFun(extras) { document.get ...

Unable to retrieve function variables stored in fancytree source nodes within its activate method

If the configuration of my fancytree includes a source like this: source: [{ title: "Item1", key: "1", myFunc: function (item) { return 'function'; ...

What is the best way to retrieve a comprehensive outcome from a sql search utilizing php and consequently showcase it using javascript?

Need help with my PHP script that executes a query and returns multiple rows? Learn how to use json_encode in conjunction with JavaScript to fetch this data and display it in a table. This code snippet echoes two JSON encoded lines, each representing one ...

Json mapping successfully pairs keys but struggles with accurately matching values

I have encountered an issue with my JSON mapping. The format works fine for the keys, but I am facing problems with the values - sometimes nothing is displayed or it shows NULL. If you have any insights on how to troubleshoot this, I would greatly apprecia ...

Transform the arrow function into a standard JavaScript function

Here is the React return code snippet I'm working with: return ( <div className='App'> <form onSubmit={this.submit.bind(this)}> <input value={this.state.input} onChange={(e) ...

Importing usernames and passwords from a .txt file with Javascript

I'm in the process of creating a website that includes a login feature. The usernames and passwords are currently stored within the website files as .txt documents. I am aware that this method is not secure, but for the purpose of this project, I want ...

Performance problem with React-Native for-looping through a large array size

I'm currently facing a performance issue with the search function in my react-native app. The search involves scanning through an array of 15,000 elements for specific keywords. Surprisingly, the search performs well and quickly on Android devices, bu ...

Transmitting form information to a nested page within a div container

This is my fourth attempt to seek an answer to this question, as I've faced downvotes in previous attempts. So here we go again. I am trying to send data from a hidden input within a form using ajax. The value of the hidden input is generated by a php ...

Unable to scroll to the top of the page with JavaScript

I tried the code below but it didn't quite do the trick. Can someone assist me with refreshing the page to the top every time it loads? window.addEventListener('load', function(){ window.scrollTo(0,0) }) window.onload = (event) => { ...

Encountering issues with MediaSession.setPositionState() and seekto functionalities not functioning properly

Having trouble with MediaSession.setPositionState() not displaying the audio time and seekbar not behaving as expected. const sound= document.querySelector('sound'); function updatePositionState() { if ('setPositionState' in navigato ...

Click on the react item to view more information

I'm brand new to React and I'm exploring the swapi API for the first time. My goal is to retrieve a list of films (movie titles) and then, when a title is clicked on, display the opening crawl from the JSON object. So far, I've been able to ...

Having trouble sending a GET request from the client to my backend route using axios in a React-Node.js/Express setup. Where did I go wrong?

Struggling with making an API request from my backend route (using nodes/express). I'm making an axios request from the client site using React. The express backend route works fine, so the issue must be in my client-side code. I've been stuck on ...

Generate a collection of elements using a different collection as a reference

I am struggling with an array of objects: let data = [{ createdDate: "2222", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="087c6d7b7c3d487c6d7b7c266b6765">[email protected]</a>", histories: [ ...

Running multiple controller functions in nodejs can be achieved by chaining them together in the desired

Currently, I am working on the boilerplate code of mean.io and adding a password reset email feature to it. Whenever a user requests a password reset with their email as a parameter, I generate a unique salt (resetid) and send them an email with a link con ...

Arrange Raphael Objects in Their Relative Positions

I've been experimenting with Raphael.js recently and I've encountered an issue related to the positioning of each Raphael object. My goal is to create multiple 'canvases' without having them overlap within a predefined div on the page. ...

Retrieving parameters from a class that is handed over from the constructor to a function by leveraging the rest parameter feature

I am encountering an issue where the Method is not reading the values in the arguments, despite my attempts to pass each argument through the constructor into the method for encryption. Could someone please point out what I might be doing wrong? class A ...

JavaScript saves all URLs using a consistent format (http, https, www.)

As a junior backend developer, my experience with JavaScript is limited. I am attempting to standardize the format of stored URLs as shown below: www.hello.com hello.com http://hello.com https://hello.com Currently, if I input hello.com, it automatically ...