I have an object that has pairs of substitute values used for simple encoding / decoding (not for security, just for convenience, it's all too difficult to explain all this here). He's in shape
var obj = {x: y,
x: y,
...
};
where "x" is the encoding value, and "y" is the decoded value.
Decoding is simple: I scroll line characters and view the value of charAt(i)the object through the brackets obj[ str.charAt(i) ]. (I can’t check if we need a uppercase or lowercase version (all keys / values in the object are lowercase), but this is quite simple.)
To encode, of course, I have to look up the value in the object, not the property. I am currently looping through properties with a loop for ... in ...and checking values by value charAt(i). My current code is:
var i, j,
output = '',
str = 'Hello World!',
obj = {'s':'d',
'm':'e',
'e':'h',
'x':'l',
'z':'o',
'i':'r',
'a':'w',
'o':'!',
'-':' '};
for (i = 0; i < str.length; i++) {
for (j in obj) {
if (Object.prototype.hasOwnProperty.call(obj, j) &&
Object.prototype.propertyIsEnumerable.call(obj, j)) {
if (obj[j] === str.charAt(i)) {
output += j;
break;
} else if (obj[j].toUpperCase() === str.charAt(i)) {
output += j.toUpperCase();
break;
}
}
}
}
alert(output);
I naturally feel that there must be a more efficient way to do this. (Of course, having a return object, {y: x}, is an option, but not a good one). Is this the best way or better? In essence, I would like to do var prop = obj[value]how I can do var value = obj[prop].