反向查找对象与数组 [英] Reverse lookup object with array

查看:95
本文介绍了反向查找对象与数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说说我是否有这样的物体

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]
};

弄清楚resourceId = 21是否为"c"的最佳方法是什么?

What is the best way to figure out if resourceId = 21 would be "c"?

我们不知道键名或键数.它只匹配一次:表示21将仅属于一个键"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".

我正在考虑遍历所有键并执行indexOf(),但是我觉得它不够优雅".

I am thinking of looping through all keys and do indexOf(), but I don't feel it's "elegant" enough.

我可以使用Underscore,但尝试避免使用Angular或jQuery或仅使用原始Javascript.

I could use Underscore but try to avoid and go with what Angular or jQuery or just vanilla Javascript.

推荐答案

拥有

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), {});

这篇关于反向查找对象与数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆