Reputation: 26605
I need to create object in javascript that allows to fetch values using keys & also iterate over keys. The primary requirement is fetching value by key but iteration is required to maintain sort order of entries by values(integer).
How do I go about creating such an object ?
Upvotes: 0
Views: 3132
Reputation: 60424
Native objects don't support exactly what you're looking for, but it's fairly straightforward to create a wrapper around native objects that provides extra functionality.
A possible approach:
function KeySortArr(obj) {
this.obj = obj || {};
}
KeySortArr.prototype = {
get: function(key) {
return this.obj[key];
},
set: function(key, value) {
this.obj[key] = value;
},
keys: function() {
var keys = [];
for(var i in this.obj) {
if (this.obj.hasOwnProperty(i))
keys.push(i);
}
return keys;
},
getKeysSortedByValue: function() {
var obj = this.obj;
return this.keys().sort(function(a, b) {
return obj[a] > obj[b];
});
}
};
Usage:
var arr = new KeySortArr();
arr.set("test", 4);
arr.set("another", 2);
arr.set("ok", 60);
arr.set("last", 14);
The following then:
arr.getKeysSortedByValue();
Returns:
["another, "test", "last", "ok"]
In other words, the keys are sorted by their associated value. This might not be exactly what you were looking for, but it should be close.
Upvotes: 0
Reputation: 309
sampleJson={
"1":"john",
"2":"johny"
}
You can iterate using for in loop
for(key in sampleJson){
//ur code
}
Upvotes: 1
Reputation: 70162
for
in
loop iterates over the keys of an object. Upvotes: 1