I have an object ( array of hashes ) and I need to convert it into ordered key value pairs.
This is object:
var places_info = [
{"place_id":180,"name":"Abc","city":"Gotham"},
{"place_id":161,"name":"Def","city":"Sin City"},
{"place_id":178,"name":"Ghi","city":"Timbuktu"},
{"place_id":179,"name":"Jkl","city":"Acapulco"},
{"place_id":174,"name":"Mno","city":"Desire"}
];
And I need function to return key/value (place_id
/name
) pairs in same (alphabetical by name
) order:
{
'180': 'Abc',
'161': 'Def',
'178': 'Ghi',
'179': 'Jkl',
'174': 'Mno'
}
Actual use: I need it as input for Jeditable Select-input (actual example on demo page). Select-type needs for data
-property key/value pairs or function which returns them. So far I got select options in random order, but--as you may imagine--I need them ordered by value....
As for Jeditable the data may be just a fake hash (string formed as JSON key/value pairs), my only solution is like this:
var arr = new Array;
for ( i in places_info ) {
arr.push( "'" + places_info[i].place_id + "':'" + places_info[i].name + "'" );
}
var uglyString = '{' + arr.join(',') + '}';
Is there some more elegant and intuitive approach for such goal? I'd like to keep my data in proper data structure. Converting it to flat string seems like hack.
Edit
I must reconsider the problem. I did not test Jeditable with generated string and seems it evals string into hash and then my desired order is gone. So, this problem needs different approach. Maybe I need make my own datatype for Jeditable. But this seems like different question.