按值查找数组的自定义字符串索引-用于多个数组

时间:2019-01-07 08:37:24

标签: javascript arrays indexof

我对数组有点问题。

我有一个字符串作为值,这是数组索引唯一的值,例如“ daa12d956752gja2”:

g_nodeMapping["87686479/welcome.html"] = "daa12d956752gja2";

我知道这个字符串。我需要获取的是索引,因此为“ 87686479 / welcome.html”。事情是...我有很多这样的数组。基本上看起来像这样:

g_nodeMapping = [];
g_nodeMapping["8374628/test.html"] = "489fa3682975da";
g_nodeMapping["8953628/anothersite.html"] = "gi764295hf46";
g_nodeMapping["267857543/helpplx.html"] = "8653468te87a";

...

我尝试了indexOf方法,但似乎没有找到等式符号后的值的数组索引。

很遗憾,我无法更改数组。

非常感谢您的帮助。抱歉,我在移动设备上。

2 个答案:

答案 0 :(得分:1)

您可以通过从对象/数组中获取所有键并找到值来找到键。

function getKey(object, value) {
    return Object.keys(object).find(k => object[k] === value);
}
   
var g_nodeMapping = [];
g_nodeMapping["8374628/test.html"] = "489fa3682975da";
g_nodeMapping["8953628/anothersite.html"] = "gi764295hf46";
g_nodeMapping["267857543/helpplx.html"] = "8653468te87a";
g_nodeMapping["87686479/welcome.html"] = "daa12d956752gja2";

console.log(getKey(g_nodeMapping, "daa12d956752gja2"));

答案 1 :(得分:0)

您可以定义一个函数findCustomKey,该函数将数组元素(或值)作为参数并返回键。以下示例显示:

var arr = [];
arr["8374628/test.html"] = "489fa3682975da";
arr["8953628/anothersite.html"] = "gi764295hf46";
arr["267857543/helpplx.html"] = "8653468te87a";

function findCustomKey(ele) {
    let keys = Object.keys(arr);
    for (let keyEle of keys) {
        if (arr[keyEle] == ele) {
            return keyEle;
        }
    }
}

console.log(findCustomKey("489fa3682975da"));
console.log(findCustomKey("8653468te87a"));
console.log(findCustomKey("abcd123"));


输出:

8374628/test.html
267857543/helpplx.html
undefined


另一个版本(已添加EDIT):

这里是findCustomKey编码的另一种方式(使用方式保持不变):

function findCustomKeyV2(ele) {
    return Object.keys(arr).filter(k => arr[k] == ele)[0];
}


另一个版本:

已添加此解决方案的版本,因为上述代码在IE浏览器上不起作用。以下代码可在Firefox,Chrome和IE11浏览器上使用。

var arr = [];
arr['8374628/test.html'] = '489fa3682975da';
arr['8953628/anothersite.html'] = 'gi764295hf46';
arr['267857543/helpplx.html'] = '8653468te87a';

var arrMap = new Map();
for (let k in arr) {
    arrMap.set(arr[k], k);
}

console.log(arrMap.get('489fa3682975da'));
console.log(arrMap.get('8653468te87a'));
console.log(arrMap.get('abcd123'));