Reputation: 420
I am trying to map a json object to an array with values associated to the keys. I need to keep keys and values associated because I will do a sort on the created array after. My object look like this :
{"178":"05HY24","179":"1HY12","292":"1HY24","180":"3HY12"}
I have tryed to do the array with this function :
value=$.map(value, function(value, key) { return key,value; });
But keys are not associated to my values. Keys are 0,1,2,3 and not 178,179,292,180. I try a lot of things but I don't know how to do that.
Upvotes: 7
Views: 25229
Reputation:
You can do it without using jQuery:
var values = {
"178": "05HY24",
"179": "1HY12",
"292": "1HY24",
"180": "3HY12"
};
var array = [];
for (var k in values)
array.push({
'k': k,
'v': values[k]
});
array.sort(function(a, b) {
return a.k - b.k;
});
console.log(array);
Upvotes: 1
Reputation: 870
var myHashMap = JSON.parse('{"178":"05HY24","179":"1HY12","292":"1HY24","180":"3HY12"}');
console.log(myHashMap[178]);
// => "05HY24"
// now map to array..
var myArray = $.map(myHashMap, function(value, index) {
return [value];
});
console.log(myArray);
Upvotes: 8