I have an object like this coming back as a JSON response from the server:
{\"0\":\"1\",\"1\":\"2\",\"2\":\"3\",\"3\":\"4\"}
I want to conv
Here is an example of how you could get an array of objects and then sort the array.
function osort(obj)
{ // map the object to an array [key, obj[key]]
return Object.keys(obj).map(function(key) { return [key, obj[key]] }).sort(
function (keya, keyb)
{ // sort(from largest to smallest)
return keyb[1] - keya[1];
}
);
}
var json = '{"0":"1","1":"2","2":"3","3":"4"}';
var parsed = JSON.parse(json);
var arr = [];
for(var x in parsed){
arr.push(parsed[x]);
}
Hope this is what you're after!
There is nothing like a "JSON object" - JSON is a serialization notation.
If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray()
method:
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();
Nothing hard here. Loop over your object elements and assign them to the array
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {
arr.push(obj[elem]);
}
http://jsfiddle.net/Qq2aM/
var obj = {"0":"1","1":"2","2":"3","3":"4"};
var vals = Object.values(obj);
console.log(vals); //["1", "2", "3", "4"]
Another alternative to the question
var vals = Object.values(JSON.parse(obj)); //where json needs to be parsed
This is best solution. I think so.
Object.keys(obj).map(function(k){return {key: k, value: obj[k]}})