Transforming the value of a property in a JSON object using JavaScript

I have a JSON object that I am trying to manipulate by changing the value of its property "quantity"

"[{"name":"Butter","image":"/static/images/items/dairy/butter.jpg",
"price":" 30 uah","quantity":"1","alias":"butter"},   
{"name":"Chesse","image":"/static/images/items/dairy/cheese.jpg",
"price":" 60 uah","quantity":"1","alias":"chesse"}]"

After accessing the property value json[0].quantity, I attempt to update it with the following code:

var quantity = parseInt(json[0].quantity); 
 json[0].quantity = String(quantity + 1);

Unfortunately, the attempted change does not take effect. The "quantity" property remains unchanged. Any assistance would be greatly appreciated.

Answer №1

To work with a JSON string, you must first parse it into JSON format. To increment the quantity property, you need to convert it to an integer using parseInt:

var jsonString = '[{"name":"Butter","image":"/static/images/items/dairy/butter.jpg","price":"30 uah","quantity":"1","alias":"butter"},{"name":"Chesse","image":"/static/images/items/dairy/cheese.jpg","price":"60 uah","quantity":"1","alias":"chesse"}]';
console.log(JSON.stringify(jsonString));
var product = JSON.parse(jsonString);
product[0].quantity = parseInt(product[0].quantity) + 1;

alert(product[0].quantity);

Answer №2

To convert this json into a JavaScript object, you can use the following method:

parsedJson = JSON.parse(json)

After parsing, you can continue using your existing code and it should function correctly. If you need to change it back into json format, simply utilize:

JSON.stringify(parsedJson)

Answer №3

The code example provided in the question appears to be incorrect and not functioning as expected.

Give this alternative code a try and observe that it works perfectly:

var data = [{
    "name": "Milk",
    "image": "/static/images/items/dairy/milk.jpg",
    "price": " 25 uah",
    "quantity": "1",
    "alias": "milk"
}];
var quantityValue = parseInt(data[0].quantity);
data[0].quantity = String(quantityValue + 1);
console.log(data[0]);

Result Output:

Object {name: "Milk", image: "/static/images/items/dairy/milk.jpg", price: " 25 uah", quantity: "2", alias: "milk"}

As shown, the quantity now displays as 2 following the manipulation.

The decision to store numeric values as strings may raise questions, but that is a separate topic for discussion.

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

"Understanding the Boolean value in the OnResponse callback of Android's Volley

Hey there, I'm a newcomer to Android development and I've encountered an issue while trying to return a boolean value based on the response inside the OnResponse method for Android Volley. Essentially, I want the boolean value to be determined by ...

Unbind a prepared statement in a node.js environment using SQL

Utilizing the node-mssql library (https://github.com/patriksimek/node-mssql) and encountered a problem when attempting to execute a second request, resulting in the following error: this.connection.pool.acquire(done); ^ TypeEr ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

The issue with CSS filter invert not functioning properly in Mozilla Firefox is causing complications

I am currently developing a small Firefox add-on designed to make reading pages at night more comfortable. The goal is to invert page colors without affecting images. Here is the code snippet I am using: document.body.style.filter = "invert(100%)"; var i ...

Is it possible to retrieve server data in a JavaScript file?

EDIT: I accidentally omitted a piece of relevant code I am looking to access the "jsonData" value from my server in my JavaScript file. Can someone guide me on how to retrieve these values? Here is the server-side code: var express = require('expre ...

Loading Fragments with Android's AsyncTask

I am currently working on implementing a JSON-populated listview in an Android fragment. The app crashes while running the AsyncTask portion, and I'm having trouble understanding the cause of the issue. I am following a tutorial that was originally in ...

What is the best way to handle incoming JSON data from my controller?

When I send this JSON to my controller: {"user_id": 234324, "user_action": 2, "updated_email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4a2b392e2c0a2b392e2c64292527">[email protected]</a>" } The JSON is c ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

Exploring a Compilation of Unconventional Thesauruses

I recently extracted data from a sports betting website API, which provided me with JSON information in the form of a list of dictionaries. My goal is to extract specific bets and their corresponding odds from this data. Below you can find the code I have ...

The 'file' property of undefined throws an error in ng-file-upload

I am currently exploring the functionality of ng-file-upload from this repository: https://github.com/danialfarid/ng-file-upload I have successfully implemented the basic setup as follows: HTML: <section ng-controller="MyController"> ...

Using TypeScript to validate the API response against specific types

I'm intrigued by the scenario where you expect a specific data type as a response from fetch / Axios / etc, but receive a different type instead. Is there a way to identify this discrepancy? interface HttpResponse<T> extends Response { parsed ...

Is ng-repeat failing to bind values in the Dom?

When loading data dynamically to ng-repeat, I am encountering an issue where the data is not binding to ul. Typically, this can happen with duplicate indexes, but in my case I'm unsure of what's causing it. Any suggestions? main.html <div> ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Tips for resetting form fields and clearing previous values before resubmitting the form, allowing for a fresh start with empty fields

Welcome to my website! If you visit , you'll notice a feature I've added that clears form field values after submission. However, I'm encountering an issue where the fields remain filled when revisiting the page for another appointment. I at ...

Is there a way to extract values from a particular object?

Currently, I am utilizing a JSON server to establish a straightforward login system. The data stored on the server is structured as follows: { "users": [ { "name": "user1", "password": "pass1", "email": "<a href="/cdn-cgi/l/emai ...

Guide to transferring a PHP variable from a loop and converting it into a JavaScript variable

I am having an issue with accessing specific row values in a while loop that displays data from a mysql table into a table. Each row has a button to send data via ajax to another PHP page for insertion into another table. However, since I am outside of the ...

How can we prevent the modal from extending beyond the boundaries of the phone screen when zoomed in

I am currently developing a web application that features a large content page, specifically a map which should display detailed information upon zooming in similar to Google Maps. The interactive elements on my map are clickable, triggering a modal popup ...

Is it possible to create an index for an associative array based on a string in JavaScript?

Within my JavaScript code, I am working with an associative (two-dimensional) array (myObj[x][y]). Each row in this array contains a different number of elements denoted by 'n', where the first value signifies the amount 'n' as shown be ...

How can I pull all data from an array using MongoDB query?

I have multiple arrays, but I am only interested in extracting the content related to "PIZZAS." Can anyone advise me on the appropriate query to achieve this? https://i.stack.imgur.com/wHolE.png ...