Javascript: Quickly lookup value in object (like we can with properties)

半腔热情 提交于 2019-11-30 20:33:59

It's more efficient to loop just once beforehand to create a reverse map:

var str = "Hello World!",
    output = '',
    map = {
      "s":"d", "m":"e",
      "e":"h", "x":"l",
      "z":"o", "i":"r",
      "a":"w", "o":"!",
      "-":" "
    },
    reverseMap = {}

for (j in map){
  if (!Object.prototype.hasOwnProperty.call(map, j)) continue
  reverseMap[map[j]] = j
}

output = str.replace(/./g, function(c){
  return reverseMap[c] || reverseMap[c.toLowerCase()].toUpperCase()
})

console.log(output)

Instead of doing str.length * map.length, you'll do map.length + str.length operations.

A reverse encoder would make more sense, but you can write a replace function without all the hasOwnProperty etc.tests.

var str= 'Hello World!',
obj={
    's':'d',
    'm':'e',
    'e':'h',
    'x':'l',
    'z':'o',
    'i':'r',
    'a':'w',
    'o':'!',
    '-':' '
}
str= str.replace(/./g, function(w){
    for(var p in obj){
        if(obj[p]=== w) return p;
        if(obj[p]=== w.toLowerCase()) return p.toUpperCase();
    };
    return w;
});

returned value: (String) Emxxz-Azixso

You can create a reversed version of the mapping programmatically (instead of by hand) and use it instead.

var rev = {}
for (key in obj)
    rev[obj[key]] = key

If you're looking for array keys check here.

https://raw.github.com/kvz/phpjs/master/functions/array/array_keys.js

function array_keys (input, search_value, argStrict) {
    var search = typeof search_value !== 'undefined', tmp_arr = [], strict = !!argStrict, include = true, key = '';

    if (input && typeof input === 'object' && input.change_key_case) {
        return input.keys(search_value, argStrict);
    }

    for (key in input) {
        if (input.hasOwnProperty(key)) {
            include = true;
            if (search) {
                if (strict && input[key] !== search_value) include = false;
                else if (input[key] != search_value) include = false;
            }
            if (include) tmp_arr[tmp_arr.length] = key;
        }
    }

    return tmp_arr;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!