change(rewrite) json object's property value in JavaScript

- 1 answer

Ad

I've got stringify JSON object in which I try to change value of it's 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"}]"

So I get property value json[0].quantity and try to rewrite it like that

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

But it's doesn't work. "quantity" property stays constant. Please help

Ad

Answer

Ad

since you have json string you first need to parse it in to json and to increment quantity property you first need it to 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);

Ad
source: stackoverflow.com
Ad