7

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.

5
  • 1
    Because array index starts from Zero Commented Jul 8, 2015 at 9:06
  • Are you basically after an array of objects? e.g. [{178: "05HY24"}, {179:"1H&12"}, etc. ] ? Commented Jul 8, 2015 at 9:07
  • My data are not in an array. I only have one object with keys assiciated to values Commented Jul 8, 2015 at 9:11
  • 1
    jsfiddle.net/arunpjohny/kaxdk5v8/1 ? Commented Jul 8, 2015 at 9:16
  • ok, but how can I sort my new array on values after? I can't use the sort function? Commented Jul 8, 2015 at 9:21

2 Answers 2

8
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);
Sign up to request clarification or add additional context in comments.

5 Comments

it still give me an object. I want an array to do array operation after
at the end if I do a console.log(myArray[292]) the result is undefined and not 1HY24. The keys are lost
@Etienne that's because it is an array, not an object - like you wanted. Edit: I'm not sure you quite know what you actually want/need - but take a look at this answer if you want to sort objects: stackoverflow.com/a/16794116/1173155
ok so I can't have keys associated to values in a javascript array. I can only have key begining to 0.
if you use myHashMap after the JSON.parse() you should have an object with keys. So you can do myHashMap.292 and it'll return 1HY24
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.