我有一个非常简单的JavaScript对象,我将其用作关联数组。是否有一个简单的函数允许我获取值的键,或者我必须迭代对象并手动找到它?


当前回答

真的很简单。

const CryptoEnum = Object.freeze({
                    "Bitcoin": 0, "Ethereum": 1, 
                    "Filecoin": 2, "Monero": 3, 
                    "EOS": 4, "Cardano": 5, 
                    "NEO": 6, "Dash": 7, 
                    "Zcash": 8, "Decred": 9 
                  });

Object.entries(CryptoEnum)[0][0]
// output => "Bitcoin"

其他回答

使用Underscore.js库:

var hash = {
  foo: 1,
  bar: 2
};

(_.invert(hash))[1]; // => 'foo'

以下是我的解决方案:

例如,我假设我们有一个包含三个值对的对象:

function findKey(object, value) {

    for (let key in object)
        if (object[key] === value) return key;

    return "key is not found";
}

const object = { id_1: "apple", id_2: "pear", id_3: "peach" };

console.log(findKey(object, "pear"));
//expected output: id_2

我们可以简单地编写一个findKey(数组,value),它接受两个参数,一个是对象,一个是你正在寻找的键的值。因此,该方法是可重用的,您不需要每次都手动迭代对象,只需为该函数传递两个参数。

如果你正在使用下划线或Lodash库,你可以使用_。findKey功能:

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

_.findKey(users, function(o) { return o.age < 40; });
// => 'barney' (iteration order is not guaranteed)

// The `_.matches` iteratee shorthand.
_.findKey(users, { 'age': 1, 'active': true });
// => 'pebbles'

// The `_.matchesProperty` iteratee shorthand.
_.findKey(users, ['active', false]);
// => 'fred'

// The `_.property` iteratee shorthand.
_.findKey(users, 'active');
// => 'barney'

或者,更简单的是—按您想要的顺序创建一个具有键和值的新对象,然后查找该对象。我们在使用上面的原型代码时发生了冲突。你不必在键周围使用String函数,那是可选的。

 newLookUpObj = {};
 $.each(oldLookUpObj,function(key,value){
        newLookUpObj[value] = String(key);
    });

这为我获得对象的键/值工作。

让obj = { “key1”:“value1”, “key2”:“value2”, “key3”:“value3”, “key4”:“value4” } 种(obj) . map函数(k) { Console.log ("key with value: "+k +" = "+obj[k]) })