Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery map an object with key and value

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.

like image 914
Etienne Avatar asked Jul 08 '15 09:07

Etienne


People also ask

What is map () in jQuery?

map() method applies a function to each item in an array or object and maps the results into a new array. Prior to jQuery 1.6, $. map() supports traversing arrays only. As of jQuery 1.6 it also traverses objects.

Can I map an object in JavaScript?

Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted.

How do you map an array of objects?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.


1 Answers

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);
like image 77
shanehoban Avatar answered Oct 05 '22 10:10

shanehoban