How to get a key in a JavaScript object by its val

2018-12-31 07:08发布

I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?

23条回答
旧时光的记忆
2楼-- · 2018-12-31 07:46

Underscore js solution

let samplLst = [{id:1,title:Lorem},{id:2,title:Ipsum}]
let sampleKey = _.findLastIndex(samplLst,{_id:2});
//result would be 1
console.log(samplLst[sampleKey])
//output - {id:2,title:Ipsum}
查看更多
素衣白纱
3楼-- · 2018-12-31 07:47

I created the bimap library (https://github.com/alethes/bimap) which implements a powerful, flexible and efficient JavaScript bidirectional map interface. It has no dependencies and is usable both on the server-side (in Node.js, you can install it with npm install bimap) and in the browser (by linking to lib/bimap.js).

Basic operations are really simple:

var bimap = new BiMap;
bimap.push("k", "v");
bimap.key("k") // => "v"
bimap.val("v") // => "k"

bimap.push("UK", ["London", "Manchester"]);
bimap.key("UK"); // => ["London", "Manchester"]
bimap.val("London"); // => "UK"
bimap.val("Manchester"); // => "UK"

Retrieval of the key-value mapping is equally fast in both directions. There are no costly object/array traversals under the hood so the average access time remains constant regardless of the size of the data.

查看更多
临风纵饮
4楼-- · 2018-12-31 07:48

Non-iteratable solution

Main function:

var keyByValue = function(value) {

    var kArray = Object.keys(greetings);        // Creating array of keys
    var vArray = Object.values(greetings);      // Creating array of values
    var vIndex = vArray.indexOf(value);         // Finding value index 

    return kArray[vIndex];                      // Returning key by value index
}

Object with keys and values:

var greetings = {
    english   : "hello",
    ukranian  : "привіт"
};

Test:

keyByValue("привіт");
// => "ukranian"
查看更多
有味是清欢
5楼-- · 2018-12-31 07:50

The lodash way https://lodash.com/docs#findKey

var users = {
  'barney':  { 'age': 36, 'active': true },
  'fred':    { 'age': 40, 'active': false },
  'pebbles': { 'age': 1,  'active': true }
};

_.findKey(users, { 'age': 1, 'active': true });
// → 'pebbles'

查看更多
低头抚发
6楼-- · 2018-12-31 07:50

Keep your prototype clean.

function val2key(val,array){
    for (var key in array) {
        if(array[key] == val){
            return key;
        }
    }
 return false;
}

Example:

var map = {"first" : 1, "second" : 2};
var key = val2key(2,map); /*returns "second"*/
查看更多
骚的不知所云
7楼-- · 2018-12-31 07:51

Given input={"a":"x", "b":"y", "c":"x"} ...

To use the first value (e.g. output={"x":"a","y":"b"}): output=Object.keys(input).reduceRight(function(accum,key,i){accum[input[key]]=key;return accum;},{})

To use the last value (e.g. output={"x":"c","y":"b"}): output=Object.keys(input).reduce(function(accum,key,i){accum[input[key]]=key;return accum;},{})

To get an array of keys for each value (e.g. output={"x":["c","a"],"y":["b"]}): output=Object.keys(input).reduceRight(function(accum,key,i){accum[input[key]]=(accum[input[key]]||[]).concat(key);return accum;},{})

查看更多
登录 后发表回答