I get data from a source in the form of a JSON. Let's say the JSON looks like this
var data = [
{"city" : "Bangalore", "population" : "2460832"}
]
I'd be passing this data object into a kendo grid and I'll be using its out-of-the-box features to format numbers. So, I need the same JSON as an object literal that looks like this
var data = [{city : "Bangalore", population: 2460832}]
Are there any libraries, functions or simple ways to achieve this?
You can iterate over the Object
s in the Array
and modify each population
property, converting its value from a string to a number with parseInt()
or similar :
var data = [
{"city" : "Bangalore", "population" : "2460832"}
];
data.forEach(function (entry) {
entry.population = parseInt(entry.population, 10);
});
console.log(data[0].population); // 2460832
console.log(typeof data[0].population); // 'number'
You can convert JSON into an object literal by following this idea:
(function() {
var json =
[
{
"id": 101,
"title": 'title 1'
},
{
"id": 103,
"title": 'title 3'
},
{
"id": 104,
"title": 'title 4'
}
];
var result = {};
for (var key in json) {
var json_temp = {}
json_temp.title = json[key].title;
result[json[key].id] = json_temp;
}
console.log(result);
})();
The output will be:
Object {
101: Object {
title: "title 1"
}
102: Object {
title: "title 2"
}
103: Object {
title: "title 3"
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.