I'm just starting with JSON, and I have a beginners question.
I have JSON data in that form:
[{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}]
Is it possible to change it, so the output will be [0,124,12,0,124]?
I'm just starting with JSON, and I have a beginners question.
I have JSON data in that form:
[{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}]
Is it possible to change it, so the output will be [0,124,12,0,124]?
In jQuery you can use this function:
function objectArrayToValueString(objectArray) {
var output = objectArray.map(function (each) {
return parseInt(each.price);
});
return JSON.stringify(output);
}
var objectArray = [{ "price": "0" }, { "price": "124" }, { "price": "12" }, { "price": "0" }, { "price": "124" }];
var result = objectArrayToValueString(objectArray);
alert(result);
you can use map function,
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
var temp = [{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}];
var arr = temp .map(function (el) {
return el.price;
});
console.log(arr)
You can use pasrseInt() function, which converts strings to integers, and JSON.parse(), which creates a javascript object from a json string.
So:
var s = '[{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}]'
var list = JSON.parse(s)
var newArray = []
for (var i = 0; i < list.length; ++i) {
var element = list[i]
var obj = {}
for (key in element) {
obj[key] = parseInt(element[key])
}
newArray.push(obj)
}
s = JSON.stringify(newArray)