change(rewrite) json object's property value in JavaScript
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
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad