简体   繁体   English

使用JavaScript和/或jQuery搜索关联的多维数组(对象)的有效方法,用于基于值的键

[英]efficient way to search an associative, multi-dimensional array (object) using JavaScript and/or jQuery for key based on value

I have an object that looks similar to this: 我有一个看起来像这样的对象:

var arr = {};

arr.planes = { prop1 : 'a', prop2 : 'b', prop3 : 'c' };
arr.trains = { prop1 : 'x', prop2 : 'y', prop3 : 'z' };
arr.autos = { prop1 : 'red', prop2 : 'orange', prop3 : 'blue' };

I am trying to write a function (that is fast and efficient) that will return the key (or array of keys if there are more than 1) of the outer-most array based on a key/value pair nested within. 我正在尝试编写一个函数(快速而有效),它将返回基于嵌套在其中的键/值对的最外层数组的键(或键数组,如果有多于1个)。 Something like: 就像是:

function getKey(obj, prop, val) {
   // do some stuff...
   return key;
}

var myKey = getKey(arr, 'prop2', 'orange');

The value of myKey should be "autos". myKey的值应该是“autos”。

I'm pretty sure this can be done with a couple of nested for loops but these arrays are rather large and I'm thinking that, especially using jquery's grep(), there has to be a better way... or maybe not - I'm just stumped at the moment. 我很确定这可以通过几个嵌套的for循环完成,但是这些数组相当大,我在想,特别是使用jquery的grep(),必须有更好的方法......或者可能不是 - 我此刻难倒。

Any insight would be greatly appreciated!! 任何见解都将非常感谢!!

Other than changing your data structure like chris suggests this is pretty much your only option: 除了更改像chris这样的数据结构外,这几乎是你唯一的选择:

function getKey(obj, prop, val) {
    var keys = [];

    for (var key in obj) {
        if (obj[key].hasOwnProperty(prop) && obj[key][prop] === val) {
            keys.push(key);                
        }            
    }

    return keys;
}

Nested loops are not required and you only go over each array element once.. pretty efficient in my opinion. 嵌套循环不是必需的,你只需要遍历每个数组元素..在我看来非常有效。

You might be surprised how fast a for loop can execute over an array in modern browsers. 您可能会惊讶于for循环在现代浏览器中对阵列执行的速度有多快。

But, you can also maintain different data structures for this. 但是,您也可以为此维护不同的数据结构。
Just use some loops to build a new object structured like so 只需使用一些循环来构建一个像这样结构化的新对象

var map = {
    prop1: {a: ["planes"], x: ["trains"], red: ["autos"]}
  , prop2: {...}
};

function getKey(prop, val) {
   return map[prop][val] || [];
}

then lookups are extremely fast from that point on. 从那时起,查找速度非常快。

I assume the values are scalar, otherwise this wont work because only scalars can be used as property names. 我假设值是标量,否则这不会起作用,因为只有标量可以用作属性名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM