Let say if I have an object like this
resourceMap = {
"a": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
"b": [11, 12],
"c": [21, 23],
"d": [54, 55, 56, 57, 510]
};
What is the best way to figure out if resourceId = 21
would be "c"
?
We don't know the key names or number of keys. It only matches once: meaning 21
will belong to only one key "c"
.
I am thinking of looping through all keys and do indexOf()
, but I don't feel it's "elegant" enough.
I could use Underscore but try to avoid and go with what Angular or jQuery or just vanilla Javascript.
JavaScript Array reverse()The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first.
It's perfectly acceptable to have numeric property names for objects in JavaScript. We can use this to our advantage to build a second object that maps everything in reverse. This will make lookups inexpensive.
var reverseMap = {};
for(var propName in resourceMap)
{
var numsArr = resourceMap[propName];
numsArr.forEach(function(num){
reverseMap[num]=propName;
});
}
console.log(reverseMap[54]); //'d'
http://jsfiddle.net/y11sbgbv/
Building the reverseMap can also be done more "functionally" (e.g. without using side-effects) as follows:
var reverseMap2 = Object.keys(resourceMap).reduce((acc, propName) =>
resourceMap[propName].reduce((a, num) => {
a[num] = propName;
return a;
}, acc), {});
Preprocess into a different look up table
var revMap = []; // or var revMap = {};
Object.keys(resourceMap).forEach(function(key) {
resourceMap[key].forEach( function (ind) {
revMap[ind] = key;
});
});
console.log(revMap[21])
or look up on demand:
resourceMap = { "a": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], "b": [11, 12], "c": [21, 23], "d": [54, 55, 56, 57, 510] };
function findMapKey (map, ind) {
var match = null;
Object.keys(map).some(function(key) {
var test = map[key].indexOf(ind)!==-1;
if (test) {
match = key;
}
return test;
});
return match;
}
console.log(findMapKey(resourceMap, 21));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With