I am getting Json string from my server as below
var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}
I want to convert it in an array like
var str = [["12:30 PM","1:00 PM"], ["11:30 AM","12:00 PM"]];
How would I do that?
I tried to convert using jQuery.parseJSON(str), but it's giving error.
I also researched a lot in stackoverflow and there seems to be many solutionfor this problem but none of the solution is working for this issue.
5 Answers 5
The str is already an object.
You could use jQuery.map method.
var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"};
var result = $.map(str, function(value, key) {
return [[key, value]];
});
Try this map example
var str = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"};
var convert = Object.keys(str).map(function(k) {
return [k, str[k]];
});
If you need support for IE <= 8, see Object.keys pollyfill and Array.prototype.map pollyfill
5 Comments
str in your questionCan you try this.
var p = {"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}
var o = [];
for (k in p) {
if (p.hasOwnProperty(k)) {
o.push([k, p[k]]);
}
}
5 Comments
for..in loops. In some circumstances they can pick up more properties than you might expectvar str = '{"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}';
object = JSON.parse(str);
var my_array = new Array();
for(var key in object ){
my_array[key] = object[key];
}
1 Comment
Assuming you're talking about actual string that you're getting from the server, you can do a plain string replacement:
var str = '{"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}';
str = str
.replace('{"','[["')
.replace('"}','"]]')
.replace('","','"],["')
.replace(/":"/g,'","')
This will make str into string representing an array. To make a real array out of it you can do something like this:
var arr;
eval('arr = ' + str);
This is the only legitimate use of eval I can advocate.
4 Comments
eval, you could use JSON.parse(str) and then map the object to a new array (see other answers)str.sort(); in the example above - str is still a string. Instead call arr.sort(); - arr being a real array
var str = '{"12:30 PM":"1:00 PM","11:30 AM":"12:00 PM"}';